步骤
使用properties创建一个Session对象
使用Session创建Message对象,然后设置邮件主题和正文,如果需要发送附件,就需要用到Multipart对象
使用Transport对象发送邮件
实例
代码已托管到 https://github.com/yangshangwei/commonUtils
依赖包
<!-- https://mvnrepository.com/artifact/com.sun.mail/javax.mail -->
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>${javax.mail.version}</version>
</dependency>
- 1
- 2
- 3
- 4
- 5
- 6
不带有附件的邮件
工具类一
package com.artisan.commonUtils.mail;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import com.sun.mail.util.MailSSLSocketFactory;
/**
*
* @ClassName: SendEmailUtil
* @Description: 发送邮件工具类
* @author: Mr.Yang
* @date: 2017年8月28日 下午4:50:35
*/
public class SendEmailUtil {
/**
*
*
* @Title: sendEmail
*
* @Description: 发送邮件工具类方法
*
* @param sendEmail
* 发件人地址
* @param sendEmailPwd
* 授权码代替密码(更安全) 授权码的获取:进入个人邮箱,点击设置–>账户, SMTP服务选项 默认情况下这个选项是不开启的。
* 点击开启腾讯会进行身份验证,身份验证通过以后,会收到一个用于使用SMTP的16位口令,
* 验证身份的过程中把收到的口令保存下来,因为后面要使用SMTP功能必须要用到这个口令。
* @param title
* 邮件标题
* @param content
* 邮件内容
* @param toEmilAddress
* 收件人地址
* @throws Exception
*
* @return: void
*/
public static void sendEmail(String sendEmail, String sendEmailPwd, String title, String content,
String[] toEmilAddress) throws Exception {
Properties props = new Properties();
// 开启debug调试,以便在控制台查看
props.setProperty("mail.debug", "true");
// 设置邮件服务器主机名
props.setProperty("mail.host", "smtp.qq.com");
// 发送服务器需要身份验证
props.setProperty("mail.smtp.auth", "true");
// 发送邮件协议名称
props.setProperty("mail.transport.protocol", "smtp");
// 开启SSL加密,否则会失败
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.ssl.socketFactory", sf);
Session session = Session.getInstance(props);
Message msg = new MimeMessage(session);
// 发送的邮箱地址
msg.setFrom(new InternetAddress(sendEmail));
// 设置标题
msg.setSubject(title);
// 设置内容
msg.setContent(content, "text/html;charset=gbk;");
Transport transport = session.getTransport();
// 设置服务器以及账号和密码
// 这里端口改成465
transport.connect("smtp.qq.com", sendEmail, sendEmailPwd);
// 发送到的邮箱地址
transport.sendMessage(msg, getAddress(toEmilAddress));
if(transport!=null){
try {
transport.close();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
/**
*
* @Title: getAddress
* @Description: 遍历收件人信息
* @param emilAddress
* @return
* @throws Exception
* @return: Address[]
*/
private static Address[] getAddress(String[] emilAddress) throws Exception {
Address[] address = new Address[emilAddress.length];
for (int i = 0; i < address.length; i++) {
address[i] = new InternetAddress(emilAddress[i]);
}
return address;
}
/**
*
*
* @Title: main
*
* @Description: 测试
*
* @param args
* @throws Exception
*
* @return: void
*/
public static void main(String[] args) throws Exception {
/**
* * @param sendEmail 发件人地址
*
* @param sendEmailPwd
* 授权码代替密码(更安全)
* @param title
* 邮件标题
* @param content
* 邮件内容
* @param toEmilAddress
* 收件人地址
*/
SendEmailUtil.sendEmail("xxxxx@qq.com", "xxxxxxx", "testEmail", "testcontent",
new String[] { "xxxxx@gmail.com", "xxxx@qq.com" });
}
}
/**
* 在发邮件过程中有的人会发送不成功,出现如下错误:
* javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure
*
* 这个是jdk导致的,jdk里面有一个jce的包,安全性机制导致的访问https会报错,官网上有替代的jar包,换掉就好了
*
* 对应包的下载地址:
* http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html
*
* 下载好后,直接替换掉本地JDK中的对应的两的包就好了。
*
*/
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
- 113
- 114
- 115
- 116
- 117
- 118
- 119
- 120
- 121
- 122
- 123
- 124
- 125
- 126
- 127
- 128
- 129
- 130
- 131
- 132
- 133
- 134
- 135
- 136
- 137
- 138
- 139
- 140
- 141
- 142
- 143
- 144
- 145
- 146
- 147
- 148
- 149
- 150
- 151
- 152
- 153
- 154
测试结果:
工具类二
#smtp server
mail.smtp.host=smtp.qq.com
#Authentication
mail.smtp.auth=true
#--------------------------------------------------------------
#Account of sender's mailbox
mail.sender.username=xxxxxxx@qq.com
#Authorization code of sender's mailbox
mail.sender.password=xxxxxxx
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
package com.artisan.commonUtils.mail;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import com.sun.mail.util.MailSSLSocketFactory;
/**
*
* @ClassName: SendMailUtil2
* @Description: 发送邮件工具类
* @author: Mr.Yang
* @date: 2017年8月28日 下午4:50:17
*/
public class SendMailUtil2 {
/**
* Message对象将存储我们实际发送的电子邮件信息,
* Message对象被作为一个MimeMessage对象来创建并且需要知道应当选择哪一个JavaMail session。
*/
private MimeMessage message;
/**
* Session类代表JavaMail中的一个邮件会话。
* 每一个基于JavaMail的应用程序至少有一个Session(可以有任意多的Session)。
*
* JavaMail需要Properties来创建一个session对象。
* 寻找"mail.smtp.host" 属性值就是发送邮件的主机
* 寻找"mail.smtp.auth" 身份验证,目前免费邮件服务器都需要这一项
*/
private Session session;
/***
* 邮件是既可以被发送也可以被受到。JavaMail使用了两个不同的类来完成这两个功能:Transport 和 Store。
* Transport 是用来发送信息的,而Store用来收信。这里我们只需要用到Transport对象。
*/
private Transport transport;
private String mailHost="";
private String sender_username="";
private String sender_password="";
private Properties properties = new Properties();
/*
* 初始化方法
*/
public SendMailUtil2(boolean debug) {
InputStream in = SendMailUtil2.class.getResourceAsStream("SMTPMailServer.properties");
try {
properties.load(in);
this.mailHost = properties.getProperty("mail.smtp.host");
this.sender_username = properties.getProperty("mail.sender.username");
this.sender_password = properties.getProperty("mail.sender.password");
// 开启SSL加密,否则会失败
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
properties.put("mail.smtp.ssl.enable", "true");
properties.put("mail.smtp.ssl.socketFactory", sf);
} catch (IOException e) {
e.printStackTrace();
} catch (GeneralSecurityException e) {
e.printStackTrace();
}
session = Session.getInstance(properties);
session.setDebug(debug);//开启后有调试信息
message = new MimeMessage(session);
}
/**
* 发送邮件
*
* @param subject
* 邮件主题
* @param sendHtml
* 邮件内容
* @param receiveUser
* 收件人地址
*/
public void doSendHtmlEmail(String subject, String emailContent,
String[] toEmailAddress) {
try {
// 发件人
//InternetAddress from = new InternetAddress(sender_username);
// 下面这个是设置发送人的Nick name
InternetAddress from = new InternetAddress(MimeUtility.encodeWord("小工匠")+" <"+sender_username+">");
message.setFrom(from);
// 邮件主题
message.setSubject(subject);
// 邮件内容,也可以使纯文本"text/plain"
message.setContent(emailContent, "text/html;charset=UTF-8");
// 保存邮件
message.saveChanges();
transport = session.getTransport("smtp");
// smtp验证 用户名和授权码
transport.connect(mailHost, sender_username, sender_password);
// 发送
transport.sendMessage(message, getAddress(toEmailAddress));
System.out.println("send email successfully ");
} catch (Exception e) {
e.printStackTrace();
}finally {
if(transport!=null){
try {
transport.close();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
}
/**
*
* @Title: getAddress
* @Description: 遍历收件人信息
* @param emilAddress
* @return
* @throws Exception
* @return: Address[]
*/
private static Address[] getAddress(String[] emilAddress) throws Exception {
Address[] address = new Address[emilAddress.length];
for (int i = 0; i < address.length; i++) {
address[i] = new InternetAddress(emilAddress[i]);
}
return address;
}
public static void main(String[] args) {
SendMailUtil2 se = new SendMailUtil2(true);// 开启调试
se.doSendHtmlEmail("1邮件主题", "邮件内容", new String[]{"xxxxx@gmail.com","xxxxxxxx@qq.com"});
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
- 113
- 114
- 115
- 116
- 117
- 118
- 119
- 120
- 121
- 122
- 123
- 124
- 125
- 126
- 127
- 128
- 129
- 130
- 131
- 132
- 133
- 134
- 135
- 136
- 137
- 138
- 139
- 140
- 141
- 142
- 143
- 144
- 145
- 146
- 147
- 148
- 149
- 150
- 151
- 152
- 153
- 154
- 155
- 156
- 157
- 158
- 159
- 160
- 161
- 162
测试结果:
带有附件的邮件
#smtp server
mail.smtp.host=smtp.qq.com
#Authentication
mail.smtp.auth=true
#--------------------------------------------------------------
#Account of sender's mailbox
mail.sender.username=xxxxxxx@qq.com
#Authorization code of sender's mailbox
mail.sender.password=xxxxxxx
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
package com.artisan.commonUtils.mail;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.BodyPart;
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 com.sun.mail.util.MailSSLSocketFactory;
/**
*
* @ClassName: SendEmailWithAttachment
* @Description: Email发送附件 [如果需要发送附件,就需要用到Multipart对象]
* @author: Mr.Yang
* @date: 2017年8月28日 下午4:49:35
*/
public class SendEmailWithAttachment {
private MimeMessage message;
private Session session;
private Transport transport;
private String mailHost = "";
private String sender_username = "";
private String sender_password = "";
private Properties properties = new Properties();
/*
* 初始化方法
*/
public SendEmailWithAttachment(boolean debug) {
InputStream in = SendEmailWithAttachment.class.getResourceAsStream("SMTPMailServer.properties");
try {
properties.load(in);
this.mailHost = properties.getProperty("mail.smtp.host");
this.sender_username = properties.getProperty("mail.sender.username");
this.sender_password = properties.getProperty("mail.sender.password");
// 开启SSL加密,否则会失败
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
properties.put("mail.smtp.ssl.enable", "true");
properties.put("mail.smtp.ssl.socketFactory", sf);
} catch (IOException e) {
e.printStackTrace();
} catch (GeneralSecurityException e) {
e.printStackTrace();
}
session = Session.getInstance(properties);
session.setDebug(debug);// 开启后有调试信息
message = new MimeMessage(session);
}
/**
* 发送邮件
*
* @param subject
* 邮件主题
* @param sendHtml
* 邮件内容
* @param receiveUser
* 收件人地址
* @param attachment
* 附件
*/
public void doSendHtmlEmail(String subject, String sendHtml, String[] receiveUsers, File attachment) {
try {
// 发件人
InternetAddress from = new InternetAddress(sender_username);
message.setFrom(from);
// 邮件主题
message.setSubject(subject);
// 向multipart对象中添加邮件的各个部分内容,包括文本内容和附件
Multipart multipart = new MimeMultipart();
// 添加邮件正文
BodyPart contentPart = new MimeBodyPart();
contentPart.setContent(sendHtml, "text/html;charset=UTF-8");
multipart.addBodyPart(contentPart);
// 添加附件的内容
if (attachment != null) {
BodyPart attachmentBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(attachment);
attachmentBodyPart.setDataHandler(new DataHandler(source));
// 网上流传的解决文件名乱码的方法,其实用MimeUtility.encodeWord就可以很方便的搞定
// 这里很重要,通过下面的Base64编码的转换可以保证你的中文附件标题名在发送时不会变成乱码
//sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
//messageBodyPart.setFileName("=?GBK?B?" + enc.encode(attachment.getName().getBytes()) + "?=");
//MimeUtility.encodeWord可以避免文件名乱码
attachmentBodyPart.setFileName(MimeUtility.encodeWord(attachment.getName()));
multipart.addBodyPart(attachmentBodyPart);
}
// 将multipart对象放到message中
message.setContent(multipart);
// 保存邮件
message.saveChanges();
transport = session.getTransport("smtp");
// smtp验证
transport.connect(mailHost, sender_username, sender_password);
// 发送
transport.sendMessage(message, getAddress(receiveUsers));
System.out.println("send success!");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (transport != null) {
try {
transport.close();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
}
/**
* @Title: getAddress
* @Description: 遍历收件人信息
* @param emilAddress
* @return
* @throws Exception
* @return: Address[]
*/
private static Address[] getAddress(String[] emilAddress) throws Exception {
Address[] address = new Address[emilAddress.length];
for (int i = 0; i < address.length; i++) {
address[i] = new InternetAddress(emilAddress[i]);
}
return address;
}
public static void main(String[] args) {
SendEmailWithAttachment se = new SendEmailWithAttachment(true);
File attached = new File("D:\\workspace\\ws-java-base\\commonUtils\\pom.xml");
se.doSendHtmlEmail("邮件主题带有附件", "邮件内容", new String[]{"yswcomeon@gmail.com"}, attached);
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
- 113
- 114
- 115
- 116
- 117
- 118
- 119
- 120
- 121
- 122
- 123
- 124
- 125
- 126
- 127
- 128
- 129
- 130
- 131
- 132
- 133
- 134
- 135
- 136
- 137
- 138
- 139
- 140
- 141
- 142
- 143
- 144
- 145
- 146
- 147
- 148
- 149
- 150
- 151
- 152
- 153
- 154
- 155
- 156
- 157
- 158
- 159
- 160
- 161
- 162
- 163
- 164
- 165
- 166
- 167
- 168
- 169
- 170
- 171
- 172
- 173
- 174
测试结果: