JavaMail 的简单使用
- 概述
邮件功能模块在大多数网站中,都是必不可少的功能模块。无论是用户注册还是重置密码,邮件都是比较常用的一个方式。本文主要介绍 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
JavaMail 的简单使用的更多相关文章
- 使用javaMail发送简单邮件
参考网页:http://blog.csdn.net/xietansheng/article/details/51673073package com.bfd.ftp.utils; import java ...
- (一)JavaMail发送简单邮件
1,导入依赖 <dependency> <groupId>com.sun.mail</groupId> <artifactId>jakarta.mail ...
- JavaMail发送简单邮件
非常简单的发送邮件实现,网上有很多啦,但还是自己写写记录下吧. package cn.jmail.test; import java.util.Properties; import javax.mai ...
- JavaMail的简单使用(自测可以发邮件)
在很多项目中我们都会遇到发送邮件的功能,发送邮件其实还是很实用的,正好今天做项目需要实现,现在来简单的整理一下发送邮件的实现. 建立邮件与服务器之间的会话 Properties props = new ...
- JavaMail(一):利用JavaMail发送简单邮件
JavaMail,提供给开发者处理电子邮件相关的编程接口.它是Sun发布的用来处理email的API.它可以方便地执行一些常用的邮件传输.但它并没有包含在JDK中,要使用JavaMail首先要下载ja ...
- 使用javaMail实现简单邮件发送
一.首先你要用来发送邮件的qq邮箱需要开通pop3/smtp服务,这个可以百度一下就知道了 二.导入所需要的jar包,我使用的是maven添加依赖 <dependency> <gro ...
- Android JavaMail
一.简介 JavaMail API提供了一种与平台无关和协议独立的框架来构建邮件和消息应用程序. JavaMail API提供了一组抽象类定义构成一个邮件系统的对象.它是阅读,撰写和发送电子信息的可选 ...
- 邮件实现详解(四)------JavaMail 发送(带图片和附件)和接收邮件
好了,进入这个系列教程最主要的步骤了,前面邮件的理论知识我们都了解了,那么这篇博客我们将用代码完成邮件的发送.这在实际项目中应用的非常广泛,比如注册需要发送邮件进行账号激活,再比如OA项目中利用邮件进 ...
- javaMail 邮件发送和接收示例,支持正文图片、html、附件(转)
转自:https://blog.csdn.net/star_fly4/article/details/52037587 一.RFC882文档简单说明 RFC882文档规定了如何编写一封简单的邮件(纯文 ...
随机推荐
- 类关系/self/特殊成员
1.依赖关系 在方法中引入另一个类的对象 2.关联关系.聚合关系.组合关系 #废话少说 直接上代码===>选课系统 # coding:utf-8 class Student(object): d ...
- ubuntu开机自启动服务管理
安装sysv-rc-conf sudo apt-get install sysv-rc-conf 执行下面,查看服务情况 sudo sysv-rc-conf 启动服务有以下两种方式 update-rc ...
- Python条件与循环
1.条件语句: 形式: if 判断语句 : 执行语句1elif 判断语句2: 执行语句2elif 判断语句3: 执行语句3#...else: 执行语句4 占位符 pass 2.循环语句 1.wh ...
- apache htaccess 一个 例子
<Files ~ "^.(htaccess|htpasswd)$"> deny from all </Files> DirectoryIndex index ...
- 最长上升子序列问题(O(n^2)算法)
[题目描述] 给定N个数,求这N个数的最长上升子序列的长度. [样例输入] 7 2 5 3 4 1 7 6 [样例输出] 4 什么是最长上升子序列? 就是给你一个序列,请你在其中求出一段不断严格上升的 ...
- C#工具类之字典扩展类
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using S ...
- vue学习—组件的定义注册
组件的定义注册 效果: 方法一: <div id="box"> <v-header></v-header> <hr /> <b ...
- dedecms 的采集
http://www.360doc.com/content/14/0521/09/13870710_379547377.shtml http://www.360doc.com/content/14/0 ...
- Go语言基础练习题系列2
1.练习1 生成一个随机数,让一个用户去猜这个数是多少? 代码示例如下: package main import ( "fmt" "math/rand" //m ...
- centos7安装与卸载软件
安装 yum install 服务名 查看服务名 rpm -qa |grep -i aerospike 或者 yum list installed | grep aerospike 卸载 yum re ...