• 概述

  邮件功能模块在大多数网站中,都是必不可少的功能模块。无论是用户注册还是重置密码,邮件都是比较常用的一个方式。本文主要介绍 JavaMail 的简单使用,方便大家快速开发,供大家参考。完整的 demo,可以从我的 GitHub 上下载:https://github.com/RexFang/java_email

  • pom.xml 配置文件
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>java_email</groupId>
<artifactId>java_email</artifactId>
<version>0.0.1-SNAPSHOT</version>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency> <dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency> <dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency> <dependency>
<groupId>xerces</groupId>
<artifactId>xercesImpl</artifactId>
<version>2.11.0</version>
</dependency> <dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
</dependencies>
</project>
  • log4j.properties  Maven 配置文件
### 设置###
log4j.rootLogger = debug,stdout,D,E ### 输出信息到控制抬 ###
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n ### 输出DEBUG 级别以上的日志到=D://work/logs/log.log ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = D://work/logs/log.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = DEBUG
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n ### 输出ERROR 级别以上的日志到=D://work/logs/error.log ###
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File =D://work/logs/error.log
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
  • email.properties 邮件配置文件
#是否开启debug调试
mail.debug=true
#发送服务器是否需要身份验证
mail.smtp.auth=true
#邮件发送端口
mail.smtp.port=25
#邮件服务器主机名
#mail.host=smtp.126.com
#mail.host=smtp.yeah.net
mail.host=smtp.sohu.com
#发送邮件协议名称
mail.transport.protocol=smtp
#发送邮件用户名
mail.user=java_email_test
#mail.user=rex_test
#发送邮件邮箱密码
#mail.pass=java123
mail.pass=test123
#发送邮件发件人
#mail.from=java_email_test@126.com
mail.from=java_email_test@sohu.com
#mail.from=rex_test@yeah.net
  • 邮件账户信息单例 EmailAuthenticator
package email;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication; /**
* user:Rex
* date:2016年12月25日 上午1:13:37
* TODO 发送邮件账户信息
*/
public class EmailAuthenticator extends Authenticator {
//创建单例邮件账户信息
private static EmailAuthenticator emailAuthenticator = new EmailAuthenticator(); /**
* user:Rex
* date:2016年12月25日 上午3:28:10
* TODO 私有化构造函数
*/
private EmailAuthenticator() { } /*
* user: Rex
* date: 2016年12月25日 上午3:33:36
* @return 返回密码校验对象
* TODO 重写获取密码校验对象方法
* @see javax.mail.Authenticator#getPasswordAuthentication()
*/
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(EmailConfig.getUser(), EmailConfig.getPass());
} public static EmailAuthenticator createEmailAuthenticator() {
return emailAuthenticator;
}
}
  • 邮件配置信息工具类 EmailConfig
package email;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties; import org.apache.log4j.Logger; /**
* user:Rex
* date:2016年12月25日 上午1:46:43
* TODO 发送邮件配置信息
*/
public class EmailConfig {
private static final Logger logger = Logger.getLogger(EmailConfig.class); public static final String MAIL_DEBUT = "mail.debug";
public static final String MAIL_SMTP_AUTH = "mail.smtp.auth";
public static final String MAIL_SMTP_PORT = "mail.smtp.port";
public static final String MAIL_HOST = "mail.host";
public static final String MAIL_TRANSPORT_PROTOCOL = "mail.transport.protocol";
public static final String MAIL_USER = "mail.user";
public static final String MAIL_PASS = "mail.pass";
public static final String MAIL_FROM = "mail.from"; //是否开启debug调试
private static String debug; //发送服务器是否需要身份验证
private static String auth; //发送邮件端口
private static String port; //邮件服务器主机名
private static String host; //发送邮件协议名称
private static String protocol; //发送邮件用户名
private static String user; //发送邮件邮箱密码
private static String pass; //发送邮件发件人
private static String from; //创建单例Session配置信息
private static Properties sessionProperties = new Properties(); //创建单例邮箱配置信息
private static EmailConfig emailConfig = new EmailConfig(); /**
* user:Rex
* date:2016年12月25日 上午2:03:48
* @throws IOException
* TODO 从配置文件中读取邮箱配置信息(比较好的方式是让用户在管理后台配置,从数据库读取邮箱配置信息)
*/
private EmailConfig() {
try {
InputStream fis = EmailConfig.class.getResourceAsStream("/email.properties");
Properties prop = new Properties();
prop.load(fis);
EmailConfig.auth = prop.getProperty(EmailConfig.MAIL_SMTP_AUTH, "false").trim();
EmailConfig.port = prop.getProperty(EmailConfig.MAIL_SMTP_PORT, "495").trim();
EmailConfig.debug = prop.getProperty(EmailConfig.MAIL_DEBUT, "false").trim();
EmailConfig.from = prop.getProperty(EmailConfig.MAIL_FROM, "java_email_test@126.com").trim();
EmailConfig.host = prop.getProperty(EmailConfig.MAIL_HOST, "smtp.126.com").trim();
EmailConfig.pass = prop.getProperty(EmailConfig.MAIL_PASS, "test123").trim();
EmailConfig.protocol = prop.getProperty(EmailConfig.MAIL_TRANSPORT_PROTOCOL, "smtp").trim();
EmailConfig.user = prop.getProperty(EmailConfig.MAIL_USER, "java_email_test").trim();
fis.close(); sessionProperties.setProperty(EmailConfig.MAIL_SMTP_AUTH, EmailConfig.auth);
sessionProperties.setProperty(EmailConfig.MAIL_SMTP_PORT, EmailConfig.port);
sessionProperties.setProperty(EmailConfig.MAIL_DEBUT, EmailConfig.debug);
sessionProperties.setProperty(EmailConfig.MAIL_HOST, EmailConfig.host);
sessionProperties.setProperty(EmailConfig.MAIL_TRANSPORT_PROTOCOL, EmailConfig.protocol);
} catch (FileNotFoundException e) {
logger.error("邮箱配置信息初始化异常", e);
} catch (IOException e) {
logger.error("邮箱配置信息初始化异常", e);
} catch (Exception e){
logger.error("邮箱配置信息初始化异常", e);
}
} public static String getDebug() {
return debug;
} public static String getAuth() {
return auth;
} public static String getHost() {
return host;
} public static String getProtocol() {
return protocol;
} public static String getUser() {
return user;
} public static String getPass() {
return pass;
} public static String getFrom() {
return from;
} public static EmailConfig createEmailConfig() {
return emailConfig;
} public static Properties getSessionProperties() {
return sessionProperties;
} public static String getPort() {
return port;
}
}
  • 邮件发送工具类 EmailUtil
package email;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List; import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.Multipart;
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; import org.apache.commons.lang3.StringUtils; /**
* user:Rex
* date:2016年12月25日 上午3:56:49
* TODO 邮件工具类
*/
public class EmailUtil {
/**
* user: Rex
* date: 2016年12月25日 上午4:29:18
* @param subject 邮件标题
* @param content 邮件内容
* @param to 收件人(多个收件人用英文逗号“,”隔开)
* @throws Exception
*/
public static void sendEmail(String subject, String content, String to) throws Exception{
Message msg = createMessage(subject, content, to, null);
// 连接邮件服务器、发送邮件
Transport.send(msg);
} /**
* user: Rex
* date: 2016年12月25日 上午4:17:11
* @param subject 邮件标题
* @param content 邮件内容
* @param to 收件人(多个收件人用英文逗号“,”隔开)
* @param type
* @param otherRecipient 抄送人或暗送人(多个抄送人或暗送人用英文逗号“,”隔开)
* @return 邮箱对象
* @throws Exception
*/
public static void sendEmail(String subject, String content, String to, RecipientType type, String otherRecipient) throws Exception{
Message msg = createMessage(subject, content, to, type, otherRecipient, null);
// 连接邮件服务器、发送邮件
Transport.send(msg);
} /**
* user: Rex
* date: 2016年12月25日 上午4:17:11
* @param subject 邮件标题
* @param content 邮件内容
* @param to 收件人(多个收件人用英文逗号“,”隔开)
* @param cc 抄送人(多个抄送人用英文逗号“,”隔开)
* @param bcc 暗送人(多个暗送人用英文逗号“,”隔开)
* @return 邮箱对象
* @throws Exception
*/
public static void sendEmail(String subject, String content, String to, String cc, String bcc) throws Exception{
Message msg = createMessage(subject, content, to, cc, bcc, null);
// 连接邮件服务器、发送邮件
Transport.send(msg);
} /**
* user: Rex
* date: 2016年12月25日 上午7:04:02
* @param subject 邮件标题
* @param content 邮件内容
* @param to 收件人(多个收件人用英文逗号“,”隔开)
* @param fileList 附件
* @throws Exception
*/
public static void sendEmail(String subject, String content, String to, List<File> fileList) throws Exception{
Message msg = createMessage(subject, content, to, fileList);
// 连接邮件服务器、发送邮件
Transport.send(msg);
} /**
* user: Rex
* date: 2016年12月25日 上午7:04:02
* @param subject 邮件标题
* @param content 邮件内容
* @param to 收件人(多个收件人用英文逗号“,”隔开)
* @param type
* @param otherRecipient 抄送人或暗送人(多个抄送人或暗送人用英文逗号“,”隔开)
* @param fileList 附件
* @throws Exception
*/
public static void sendEmail(String subject, String content, String to, RecipientType type, String otherRecipient, List<File> fileList) throws Exception{
Message msg = createMessage(subject, content, to, type, otherRecipient, fileList);
// 连接邮件服务器、发送邮件
Transport.send(msg);
} /**
* user: Rex
* date: 2016年12月25日 上午7:04:02
* @param subject 邮件标题
* @param content 邮件内容
* @param to 收件人(多个收件人用英文逗号“,”隔开)
* @param cc 抄送人(多个抄送人用英文逗号“,”隔开)
* @param bcc 暗送人(多个暗送人用英文逗号“,”隔开)
* @param fileList 附件
* @throws Exception
*/
public static void sendEmail(String subject, String content, String to, String cc, String bcc, List<File> fileList) throws Exception{
Message msg = createMessage(subject, content, to, cc, bcc, fileList);
// 连接邮件服务器、发送邮件
Transport.send(msg);
} /**
* user: Rex
* date: 2016年12月25日 上午7:02:07
* @param subject 邮件标题
* @param content 邮件内容
* @param to 收件人(多个收件人用英文逗号“,”隔开)
* @param cc 抄送人(多个抄送人用英文逗号“,”隔开)
* @param bcc 暗送人(多个暗送人用英文逗号“,”隔开)
* @param fileList 附件
* @return 邮箱对象
* @throws Exception
*/
private static Message createMessage(String subject, String content, String to, String cc, String bcc, List<File> fileList) throws Exception{
Message msg = createMessage(subject, content, to, RecipientType.CC, cc, fileList);
msg.setRecipients(RecipientType.BCC, InternetAddress.parse(bcc));
msg.setSentDate(new Date()); //设置信件头的发送日期 return msg;
} /**
* user: Rex
* date: 2016年12月25日 上午7:02:07
* @param subject 邮件标题
* @param content 邮件内容
* @param to 收件人(多个收件人用英文逗号“,”隔开)
* @param otherRecipient 抄送人或暗送人(多个抄送人或暗送人用英文逗号“,”隔开)
* @param fileList 附件
* @return 邮箱对象
* @throws Exception
*/
private static Message createMessage(String subject, String content, String to, RecipientType type, String otherRecipient, List<File> fileList) throws Exception{
Message msg = createMessage(subject, content, to, fileList);
msg.setRecipients(type, InternetAddress.parse(otherRecipient)); return msg;
} /**
* user: Rex
* date: 2016年12月25日 上午7:02:07
* @param subject 邮件标题
* @param content 邮件内容
* @param to 收件人(多个收件人用英文逗号“,”隔开)
* @param fileList 附件
* @return 邮箱对象
* @throws Exception
*/
private static Message createMessage(String subject, String content, String to, List<File> fileList) throws Exception{
checkEmail(subject, content, fileList);
//邮件内容
Multipart mp = createMultipart(content, fileList);
Message msg = new MimeMessage(createSession());
msg.setFrom(new InternetAddress(EmailConfig.getFrom()));
msg.setSubject(subject);
msg.setRecipients(RecipientType.TO, InternetAddress.parse(to));
msg.setContent(mp); //Multipart加入到信件
msg.setSentDate(new Date()); //设置信件头的发送日期 return msg;
} /**
* user: Rex
* date: 2016年12月25日 上午9:01:12
* @param content 邮件正文内容
* @param fileList 附件
* @return 邮件内容对象
* @throws MessagingException
* @throws UnsupportedEncodingException
* Multipart
* TODO 创建邮件正文
*/
private static Multipart createMultipart(String content, List<File> fileList) throws MessagingException, UnsupportedEncodingException{
//邮件内容
Multipart mp = new MimeMultipart();
MimeBodyPart mbp = new MimeBodyPart();
mbp.setContent(content, "text/html;charset=gb2312");
mp.addBodyPart(mbp); if(fileList!=null && fileList.size()>0){
//附件
FileDataSource fds;
for(File file : fileList){
mbp=new MimeBodyPart();
fds = new FileDataSource(file);//得到数据源
mbp.setDataHandler(new DataHandler(fds)); //得到附件本身并至入BodyPart
mbp.setFileName(MimeUtility.encodeText(file.getName())); //得到文件名同样至入BodyPart
mp.addBodyPart(mbp);
}
} return mp;
} /**
* user: Rex
* date: 2016年12月25日 上午9:48:18
* @param title 邮件标题
* @param content 邮件正文
* @param fileList 邮件附件
* void
* TODO 校验邮件内容合法性
* @throws Exception
*/
private static void checkEmail(String subject, String content, List<File> fileList) throws Exception{
if(StringUtils.isEmpty(subject)){
throw new Exception("邮件标题不能为空");
} if(StringUtils.isEmpty(content) && (fileList==null || fileList.size()==0)){
throw new Exception("邮件内容不能为空");
}
} /**
* user: Rex
* date: 2016年12月25日 上午4:01:47
* @return
* Session
* TODO 创建邮箱上下文
*/
private static Session createSession(){
return Session.getDefaultInstance(EmailConfig.getSessionProperties(), EmailAuthenticator.createEmailAuthenticator());
}
}
  • 邮件发送测试类 EmailUtilTest
package test;

import java.io.File;
import java.util.ArrayList;
import java.util.List; import org.junit.Before;
import org.junit.Test; import email.EmailUtil; public class EmailUtilTest { @Before
public void setUp() throws Exception { } @Test
public void testSendEmail() {
try {
String title = "利比亚客机遭劫持6大疑问:劫机者怎样通过安检的(1)";
String content = "当地时间23日,俄罗斯总统普京在莫斯科国际贸易中心举行年度记者会。记者会持续了近4个小时,普京一共回答了来自俄罗斯各个地区及全世界记者的47个问题。自2001年起,普京都会在每年12月中下旬举行年度记者会,这是他的第12次记者会。";
List<File> fileList = new ArrayList<File>();
fileList.add(new File("C:/Users/Rex/Desktop/log4j.properties"));
EmailUtil.sendEmail(title, content, "rex_test@yeah.net", "123@qq.com", "456@qq.com", fileList);
} catch (Exception e) {
e.printStackTrace();
}
}
}

  完整的 demo ,请查看我的 GitHub https://github.com/RexFang/java_email

欢迎转载,转载必须标明出处

最新文章

  1. Linux下MongoDB服务安装
  2. Linux入门50指令
  3. Highcharts动态添加点数据
  4. (C++) LNK2019: unresolved external symbol.
  5. [SVN Mac自带SVN结合新浪SAE进行代码管理]
  6. VS上利用C#实现一个简单的串口程序记录
  7. Content is not allowed in prolog.解决方法
  8. Discuz! 的编码规范
  9. iOS学习笔记---c语言第八天
  10. 自己构建MVC中的M
  11. hdu2011
  12. 【转载】计算机视觉(CV)前沿国际国内期刊与会议
  13. 关于XML的DTD概述
  14. WebApi 自定义过滤器实现支持AJAX跨域的请求
  15. Oracle数据库用户权限和管理员权限
  16. elasticsearch单例模式连接
  17. VirtualBox Network Config
  18. [Swift]LeetCode921.使括号有效的最少添加 | Minimum Add to Make Parentheses Valid
  19. aop(权限控制)
  20. chrome下调试安卓app 之 ionic

热门文章

  1. linode出现以下报错
  2. [Leetcode]015. 3Sum
  3. 10-排序5 PAT Judge (25 分)
  4. python中 列表 字典 元组的了解
  5. 通过JS,按照原比例控制图片尺寸
  6. WebService、WCF、WebAPI、MVC的区别
  7. VMware硬盘空间&mdash;&mdash;扩容
  8. mapreduce去重
  9. spring mvc源码分析
  10. PHP速学