Java采用SMTP协议发送邮件 转载
示例中需要用到两个包:mail.jar和activation.jar,其下载地址为:
http://java.sun.com/products/javamail/downloads/index.html
http://java.sun.com/javase/technologies/desktop/javabeans/jaf/downloads/index.html
下载后解压,将mail.jar和activation.jar放到project里的lib文件夹中,为其配置环境变量,或在myEclipse里的"Java Build Path"中将其添加到"Libraries"。
project里有三个类:入口类(TestJavaMail)、邮件信息类(MailBean)和发送邮件类(SendMail)
MailBean.java
package test3;
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)
import java.util.Vector;
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)
public class MailBean {
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)
private String to; // 收件人
private String from; // 发件人
private String host; // SMTP主机
private String username; // 发件人的用户名
private String password; // 发件人的密码
private String subject; // 邮件主题
private String content; // 邮件正文
Vector<String> file; // 多个附件
private String filename; // 附件的文件名
public String getTo() {
return to;
}
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)
public void setTo(String to) {
this.to = to;
}
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)
public String getFrom() {
return from;
}
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)
public void setFrom(String from) {
this.from = from;
}
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)
public String getHost() {
return host;
}
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)
public void setHost(String host) {
this.host = host;
}
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)
public String getUsername() {
return username;
}
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)
public void setUsername(String username) {
this.username = username;
}
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)
public String getPassword() {
return password;
}
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)
public void setPassword(String password) {
this.password = password;
}
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)
public String getSubject() {
return subject;
}
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)
public void setSubject(String subject) {
this.subject = subject;
}
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)
public String getContent() {
return content;
}
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)
public void setContent(String content) {
this.content = content;
}
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)
public String getFilename() {
return filename;
}
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)
public void setFilename(String filename) {
this.filename = filename;
}
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)
public Vector<String> getFile(){
return file;
}
public void attachFile(String fileName) {
if(file == null)
file = new Vector<String>();
file.addElement(fileName);
}
}
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)
SendMail.java
package test3;
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)
import java.util.Date;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Vector;
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)
public class SendMail {
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)
public String toChinese(String text) {
try {
text = MimeUtility.encodeText(new String(text.getBytes(), "GB2312"), "GB2312", "B");
} catch (Exception e) {
e.printStackTrace();
}
return text;
}
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)
public boolean sendMail(MailBean mb) {
String host = mb.getHost();
final String username = mb.getUsername();
final String password = mb.getPassword();
String from = mb.getFrom();
String to = mb.getTo();
String subject = mb.getSubject();
String content = mb.getContent();
String fileName = mb.getFilename();
Vector<String> file = mb.getFile();
Properties props = System.getProperties();
props.put("mail.smtp.host", host); // 设置SMTP的主机
props.put("mail.smtp.auth", "true"); // 需要经过验证
Session session = Session.getInstance(props, new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)
try {
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = {new InternetAddress(to)};
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject(toChinese(subject));
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)
Multipart mp = new MimeMultipart();
MimeBodyPart mbpContent = new MimeBodyPart();
mbpContent.setText(content);
mp.addBodyPart(mbpContent);
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)
/* 往邮件中添加附件 */
Enumeration<String> efile = file.elements();
while (efile.hasMoreElements()) {
MimeBodyPart mbpFile = new MimeBodyPart();
fileName = efile.nextElement().toString();
FileDataSource fds = new FileDataSource(fileName);
mbpFile.setDataHandler(new DataHandler(fds));
mbpFile.setFileName(toChinese(fds.getName()));
mp.addBodyPart(mbpFile);
}
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)
msg.setContent(mp);
msg.setSentDate(new Date());
Transport.send(msg);
} catch (MessagingException me) {
me.printStackTrace();
return false;
}
return true;
}
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)
}
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)
TestJavaMail.java
package test3;
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)
public class TestJavaMail {
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)
public static void main(String[] args) {
MailBean mb = new MailBean();
mb.setHost("smtp.163.com"); // 设置SMTP主机(163),若用126,则设为:smtp.126.com
mb.setUsername("linyiteng1220"); // 设置发件人邮箱的用户名
mb.setPassword("******"); // 设置发件人邮箱的密码,需将*号改成正确的密码
mb.setFrom("linyiteng1220@163.com"); // 设置发件人的邮箱
mb.setTo("linyiteng1220@126.com"); // 设置收件人的邮箱
mb.setSubject("测试_JavaMail"); // 设置邮件的主题
mb.setContent("本邮件中包含三个附件,请检查!"); // 设置邮件的正文
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)
mb.attachFile("E:\工作报告(林乙腾).doc"); // 往邮件中添加附件
mb.attachFile("E:\test.txt");
mb.attachFile("E:\test.xls");
SendMail sm = new SendMail();
System.out.println("正在发送邮件...");
if(sm.sendMail(mb)) // 发送邮件
System.out.println("发送成功!");
else
System.out.println("发送失败!");
}
}
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)
如果你用myEclipse进行开发的话,运行时可能会出现以下的错误:
Exception in thread "main" java.lang.NoClassDefFoundError: com/sun/mail/util/LineInputStream
解决方法:移除myEclipse自带的EE包
。
但你可能还需要用到EE包里的servlet相关类,那可以从Tomcat的lib文件夹中复制servlet-api.jar到project中,用它来代替EE包,一切OK!
另外,个人测试时发现无法通过新注册的网易邮箱来发邮件,以前旧的就没有问题,不知道是什么原因。
如果要通过gmail发邮件的话,请在代码Properties props = System.getProperties();后再添加以下两行代码:
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.starttls.enable","true");