java web邮件发送功能的实现
最近负责一个java web项目,需要用实现邮件发送的功能,于是就研究了一下。发现有多种实现方式,一种是比较传统的JavaMail的实现,这是用java自带的类库实现,但是实现起来比较麻烦,第二种是用Apache Commons Mail实现,需要依赖commons-email-1.2.jar包,有兴趣的可以参照http://commons.apache.org/proper/commons-email/userguide.html 我写了一个小测试,在这里分享给大家,希望能提供一下帮助。
public class MailAction extends ActionSupport {
/**
* 发送基本文本格式邮件
* @return
*/
public String sendSimpleEmail(){
SimpleEmail email = new SimpleEmail();
try {
email.setHostName("smtp.163.com"); //设置发送主机的服务器地址
email.addTo("xxx"); //设置收件人邮箱
email.setFrom("xxx"); //发件人邮箱
//email.setSSL(Boolean.TRUE); // 设定是否使用SSL
//email.setSslSmtpPort("465"); // 设定SSL端口
//设置发件人在邮件服务器上注册的用户名和密码
email.setAuthentication("用户名", "密码");
//设置主题的字符集
email.setCharset("UTF-8");
email.setSubject("你好, 这是邮件主题"); //设置邮件的主题
email.buildMimeMessage();
//邮件正文内容
email.getMimeMessage().setText("这是邮件正文部分","UTF-8");
//email.setMsg("这是邮件正文部分");
email.sendMimeMessage();
} catch (Exception e) {
e.printStackTrace();
return INPUT;
}
return SUCCESS;
}
/**
* 发送文本格式,可以添加附件
* @return
*/
public String sendMultiEmail(){
//附件,可以定义多个附件对象
EmailAttachment attachment = new EmailAttachment();
attachment.setPath("D:\\message.txt");
attachment.setDisposition(EmailAttachment.ATTACHMENT);
attachment.setDescription("附件描述");
MultiPartEmail email = new MultiPartEmail();
try {
email.setHostName("smtp.163.com"); //设置发送主机的服务器地址
email.addTo("xxx"); //设置收件人邮箱
email.setFrom("xxx"); //发件人邮箱
//设置发件人在邮件服务器上注册的用户名和密码
email.setAuthentication("用户名", "密码");
//设置主题的字符集
email.setCharset("UTF-8");
email.setSubject("你好, 这是邮件主题"); //设置邮件的主题
//邮件正文内容
email.setMsg("这是邮件正文部分");
email.attach(attachment); //添加附件
email.send();
} catch (Exception e) {
e.printStackTrace();
return INPUT;
}
return SUCCESS;
}
/**
* 发送html格式文本
* @return
*/
public String sendHtmlEmail(){
HtmlEmail email = new HtmlEmail();
try {
email.setHostName("smtp.163.com"); //设置发送主机的服务器地址
email.addTo("xxx"); //设置收件人邮箱
email.setFrom("xxx"); //发件人邮箱
//设置发件人在邮件服务器上注册的用户名和密码
email.setAuthentication("用户名", "密码");
//设置主题的字符集
email.setCharset("UTF-8");
email.setSubject("你好, 这是邮件主题"); //设置邮件的主题
//嵌入图片
URL url = new URL("http://www.apache.org/images/asf_logo_wide.gif");
String cid = email.embed(url, "Apache logo");
//设置HTML文本
email.setHtmlMsg("The apache logo -
"+
"http://www.baidu.com");
//设置基本文本,如果不支持HTML格式文本,将被替换
email.setTextMsg("你的邮箱客户端不支持HTML格式的文本");
email.send(); //发送
} catch (Exception e) {
e.printStackTrace();
return INPUT;
}
return SUCCESS;
}