最近在一个项目中需要有一个“领导邮箱”这样的功能,说白了就是在线发送邮件,想到用JavaMail来实现,因为之前没用过这个API,所以先到网上查了相关资料,经过自己整理把它封装成了一个工具包,现在把它贴出来希望对大家有用。
先了解下发送电子邮件需要用到的一些协议:
SMTP:简单邮件传输协议(Simple Mail Transfer Protocol,SMTP)由RFC821定义,它定义了发送邮件的机制,在JavaMail环境中,基于JavaMail的程序将和因特网服务供应商ISP(internet Service Provider ’ s)SMTP服务器通信.SMTP服务器会中转消息给接收方SMTP服务器以便最终让用户经由POP或者IMAP获得.
MIME:是因特网邮件扩展标准(Multipurpose Internet Mail Extensions).它不是邮件传输协议,但是对于传输的内容的消息,附件以及其他的内容定义了格式.可以理解成一个定义合适的标准.
啥也不说了,先上代码。
package tk.sagewolf.util;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.Properties;
import javax.mail.BodyPart;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Message.RecipientType;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class JM {
public static void main(String[] args) {
JM jm=new JM("smtp.163.com", "[email protected]", new String[]{"[email protected]"}, true);
jm.setAccount("[email protected]", "your password");
jm.send("邮件测试", "<h1 style='color:red;'>邮件正文</h1>");
}
private String smtpHost;
private String mailFrom;
private String[] mailTo;
private boolean auth=true;
private String user;
private String password;
private String subject;
private String content;
public JM(String smtpHost, String mailFrom, String[] mailTo, boolean auth) {
super();
this.smtpHost = smtpHost;
this.mailFrom = mailFrom;
this.mailTo = mailTo;
this.auth = auth;
}
public JM(String smtpHost, String mailFrom, String[] mailTo, boolean auth,
String user, String password, String subject, String content) {
super();
this.smtpHost = smtpHost;
this.mailFrom = mailFrom;
this.mailTo = mailTo;
this.auth = auth;
this.user = user;
this.password = password;
this.subject = subject;
this.content = content;
}
/**
* 发送邮件
* @param subject
* 邮件主题
* @param content
* 邮件内容
*/
public void send(String subject,String content){
this.subject=subject;
this.content=content;
this.send();
}
/**
* 发送邮件
*/
public void send(){
//在使用smtpHost之前将它转换成IP地址形式,否则有时候发送不了,原因未知
try {
smtpHost=InetAddress.getByName(smtpHost).getHostName();
} catch (UnknownHostException e2) {
e2.printStackTrace();
}
Session session=getSession(smtpHost);
session.setDebug(true);
MimeMessage msg=new MimeMessage(session);
//设置发件人
try {
msg.setFrom(new InternetAddress(mailFrom));
} catch (AddressException e) {
System.out.println("发件人地址格式错误!");
e.printStackTrace();
} catch (MessagingException e) {
System.out.println("设置发件人地址出错!");
e.printStackTrace();
}
//设置收件人
for(String add:mailTo){
try {
msg.addRecipient(RecipientType.TO, new InternetAddress(add));
} catch (AddressException e) {
System.out.println("收件人地址格式错误!");
e.printStackTrace();
} catch (MessagingException e) {
System.out.println("设置收件人地址出错!");
e.printStackTrace();
}
}
//设置主题
try {
msg.setSubject(subject);
} catch (MessagingException e) {
System.out.println("设置主题出错!");
e.printStackTrace();
}
//设置内容
Multipart mul=new MimeMultipart(); //MineMultipart对象来存放多个BodyPart
BodyPart mp=new MimeBodyPart(); //存放邮件内容的BodyPart对象
try {
mp.setContent(content, "text/html;charset=utf-8");
mul.addBodyPart(mp);
msg.setContent(mul);
} catch (MessagingException e) {
System.out.println("设置内容出错!");
e.printStackTrace();
}
//设置发送时间
try {
msg.setSentDate(new Date());
} catch (MessagingException e) {
System.out.println("设置发送时间出错!");
e.printStackTrace();
}
try {
msg.saveChanges(); //报纸报头域同回话内容保持一致
} catch (MessagingException e1) {
e1.printStackTrace();
}
try {
Transport transport = session.getTransport("smtp");
//发送邮件
System.out.println(smtpHost);
transport.connect(smtpHost, user, password);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
/**
* 设置发送邮箱帐号
* @param username
* 账户
* @param password
* 密码
*/
public void setAccount(String username, String password){
this.user=username;
this.password=password;
}
/**
* 得到邮件回话
*
* @return
*/
private Session getSession(String smtpHost){
Properties props=System.getProperties();
props.put("mail.smtp.host", smtpHost);
//是否需要认证,一般情况下都是的,如果你用的内部邮件服务器另谈
props.put("mail.smtp.auth", auth);
Session session=Session.getDefaultInstance(props);
return session;
}
public void setSmtpHost(String smtpHost) {
this.smtpHost = smtpHost;
}
public void setMailFrom(String mailFrom) {
this.mailFrom = mailFrom;
}
public void setMailTo(String[] mailTo) {
this.mailTo = mailTo;
}
public void setAuth(boolean auth) {
this.auth = auth;
}
public void setUser(String user) {
this.user = user;
}
public void setPassword(String password) {
this.password = password;
}
public void setContent(String content) {
this.content = content;
}
}
代码中的邮箱和密码改成真实可用的就可以,确保你的邮箱开通了SMTP服务,下面上两张截图说明163邮箱和QQ邮箱怎么开通SMTP服务,经我测试这两个邮箱都可以正常发送邮件的。
如果在把附件中的项目导入MyEcplise中测试出错,请把MyEcplise自带的javaee.jar(我的目录是D:\Program Files\Genuitec\Common\plugins\com.genuitec.eclipse.j2eedt.core_8.6.0.me201007292038\data\libraryset\EE_5)解开把其中的mail文件夹删掉再打包,注意如果你是用Winrar打包的话,请选择Zip格式的。
好了,就这样了,第一次发帖,欢迎拍砖!!!!