java发送邮件

环境

jdk1.8
activation.jar
javax.mail-1.6.2.jar
log4j-1.2.12.jar
commons-logging-1.1.1.jar

配置

开启服务

以qq邮箱为例,开启POP3/SMTP-IMAP/SMTP服务
邮箱-设置-账户


生成授权码之后一定要记住,代码中会用到

代码

com.email.util下EmailUtil.java

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
175
176
177
package com.email.util;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import org.apache.log4j.Logger;
import java.io.File;
import java.util.Properties;
/**
* 封装Email相关的操作
*/
public final class EmailUtil {
private static Logger logger = Logger.getLogger(EmailUtil.class);
private Properties properties = new Properties();
/**
* Message对象将存储我们实际发送的电子邮件信息,
*/
private MimeMessage message;

/**
* Session类代表JavaMail中的一个邮件会话。
*/
private Session session;


private Transport transport;
private String mailHost = "";
private int port = 465;
private boolean auth = false;
private String sender_username = "";
private String sender_password = "";

/**
* 初始化方法
*/
public EmailUtil(boolean debug) {
this.mailHost = EmailPropertiesUtil.getProperty("mail.smtp.host");
this.port = Integer.valueOf(EmailPropertiesUtil.getProperty("mail.smtp.port"));
this.auth = Boolean.parseBoolean(EmailPropertiesUtil.getProperty("mail.smtp.auth"));
this.sender_username = EmailPropertiesUtil.getProperty("mail.sender.username");
this.sender_password = EmailPropertiesUtil.getProperty("mail.sender.password");
properties.put("mail.smtp.host", mailHost);
properties.put("mail.smtp.auth", auth);
properties.put("mail.smtp.port", String.valueOf(port));
properties.put("mail.sender.username", sender_username);
properties.put("mail.sender.password", sender_password);
properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

session = Session.getInstance(properties);
session.setDebug(debug);//开启后有调试信息
message = new MimeMessage(session);
}

/**
* 发送邮件
*
* @param subject 邮件主题
* @param sendHtml 邮件内容
* @param receiveUser 收件人地址
*/
public void doSendHtmlEmail(String subject, String sendHtml, String receiveUser) {
try {
// 发件人
InternetAddress from = new InternetAddress(sender_username);
// 下面这个是设置发送人的Nick name
//InternetAddress from = new InternetAddress(MimeUtility.encodeWord("幻影") + " <" + sender_username + ">");
message.setFrom(from);

// 收件人
InternetAddress to = new InternetAddress(receiveUser);
message.setRecipient(Message.RecipientType.TO, to);//还可以有CC、BCC

// 邮件主题
message.setSubject(subject);

String content = sendHtml.toString();
// 邮件内容,也可以使纯文本"text/plain"
message.setContent(content, "text/html;charset=UTF-8");

// 保存邮件
message.saveChanges();

transport = session.getTransport("smtp");
// smtp验证,就是你用来发邮件的邮箱用户名密码
logger.info("授权码:"+sender_password);
transport.connect(mailHost, port, sender_username, sender_password);
// 发送
transport.sendMessage(message, message.getAllRecipients());
//System.out.println("send success!");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (transport != null) {
try {
transport.close();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
}

/**
* 发送邮件
*
* @param subject 邮件主题
* @param sendHtml 邮件内容
* @param receiveUser 收件人地址
* @param attachment 附件
*/
public void doSendHtmlEmail(String subject, String sendHtml, String receiveUser, File attachment) {
try {
// 发件人
InternetAddress from = new InternetAddress(sender_username);
message.setFrom(from);

// 收件人
InternetAddress to = new InternetAddress(receiveUser);
message.setRecipient(Message.RecipientType.TO, to);

// 邮件主题
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, port, sender_username, sender_password);
// 发送
transport.sendMessage(message, message.getAllRecipients());

logger.info("send success!");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (transport != null) {
try {
transport.close();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
EmailUtil eu = new EmailUtil(true);
eu.doSendHtmlEmail("ceshi", "这是一个测试邮件", "himingwang@126.com");
}
}

com.email.util下EmailPropertiesUtil.java

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
package com.email.util;
import java.io.IOException;
import java.util.Properties;
/**
* @author wangming
* @version
* 读取获取配置文件相关信息
* */
public class EmailPropertiesUtil {
private static Properties p = System.getProperties();
private static EmailPropertiesUtil propertiesUtil = null;
private EmailPropertiesUtil(){
try {
p.load(EmailPropertiesUtil.class.getResourceAsStream("email.properties"));
} catch (IOException e) {
e.printStackTrace();
}
}

public static String getProperty(String key){
if(propertiesUtil == null){
propertiesUtil = new EmailPropertiesUtil();
}
return p.getProperty(key);
}

public static void clear(){
p.clear();
}
}

com.email.util下email.properties

1
2
3
4
5
mail.smtp.host=smtp.qq.com
mail.smtp.port=465
mail.smtp.auth=true
mail.sender.username=账户地址
mail.sender.password=16位授权码

src下log4j.properties

1
2
3
4
5
6
log4j.logger.com.opslab.util = ERROR
log4j.rootLogger = ERROR , stdout
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 =%d{yyyy-MM-dd HH:mm:ss} %5p [%c:%L] - %m%n

成功结果

git克隆地址

https://github.com/syxiaowanzi/send-mail-util.git

本文标题:java发送邮件

文章作者:wangming

发布时间:2019年01月22日 - 01:36:27

最后更新:2019年01月22日 - 23:36:05

原始链接:https://syxiaowanzi.github.io/2019/01/22/java发送邮件/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

0%