jar包:

javax.mail-1.5.5.jar

maven配置:

        <dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.5.5</version>
</dependency>

代码:

package com.test;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties; import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
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 org.apache.log4j.Logger;
import com.test.MailAuthenticator; public class SendMail { // 日志记录
private static Logger logger = Logger.getLogger(SendMail.class); public static MailAuthenticator authenticator;
private MimeMessage message;
private Session session;
private Transport transport;
private Properties properties = new Properties(); private String mailHost = null;
private String sender_username = null;
private String sender_password = null; /**
* 构造方法
*/
public SendMail() {
super();
} /**
* 供外界调用的发送邮件接口
*/
public boolean sendEmail(String title, String content, List<String> receivers, List<File> fileList) {
try {
// 初始化smtp发送邮件所需参数
initSmtpParams(); // 发送邮件
doSendHtmlEmail(title, content, receivers, fileList); } catch (Exception e) {
logger.error(e);
}
return true;
} /**
* 初始化smtp发送邮件所需参数
*/
private boolean initSmtpParams() { mailHost = "邮箱smtp服务器"; // 邮箱类型不同值也会不同
sender_username = "发件人邮箱";
sender_password = "发件人邮箱密码"; properties.put("mail.smtp.host", mailHost);// mail.envisioncitrix.com
properties.put("mail.smtp.auth", "true");
properties.put("mail.transport.protocol", "smtp");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.ssl.checkserveridentity", "false");
properties.put("mail.smtp.ssl.trust", mailHost); authenticator = new MailAuthenticator(sender_username, sender_password);
session = Session.getInstance(properties, authenticator);
session.setDebug(false);// 开启后有调试信息
message = new MimeMessage(session); return true;
} /**
* 发送邮件
*/
private boolean doSendHtmlEmail(String title, String htmlContent, List<String> receivers, List<File> fileList) {
try {
// 发件人
InternetAddress from = new InternetAddress(sender_username);
message.setFrom(from); // 收件人(多个)
InternetAddress[] sendTo = new InternetAddress[receivers.size()];
for (int i = 0; i < receivers.size(); i++) {
sendTo[i] = new InternetAddress(receivers.get(i));
}
message.setRecipients(MimeMessage.RecipientType.TO, sendTo); // 邮件主题
message.setSubject(title); // 添加邮件的各个部分内容,包括文本内容和附件
Multipart multipart = new MimeMultipart(); // 添加邮件正文
BodyPart contentPart = new MimeBodyPart();
contentPart.setContent(htmlContent, "text/html;charset=UTF-8");
multipart.addBodyPart(contentPart); // 遍历添加附件
if (fileList != null && fileList.size() > 0) {
for (File file : fileList) {
BodyPart attachmentBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(file);
attachmentBodyPart.setDataHandler(new DataHandler(source));
attachmentBodyPart.setFileName(file.getName());
multipart.addBodyPart(attachmentBodyPart);
}
} // 将多媒体对象放到message中
message.setContent(multipart); // 保存邮件
message.saveChanges(); // SMTP验证,就是你用来发邮件的邮箱用户名密码
transport = session.getTransport("smtp");
transport.connect(mailHost, sender_username, sender_password); // 发送邮件
transport.sendMessage(message, message.getAllRecipients()); System.out.println(title + " Email send success!");
} catch (Exception e) {
logger.error(e);
} finally {
if (transport != null) {
try {
transport.close();
} catch (MessagingException e) {
logger.error(e);
}
}
}
return true;
} /**
* 测试main
*/
public static void main(String[] args) {
// 邮件主题
String title = "邮件主题"; // 邮件正文
String htmlContent = "邮件内容"; // 收件人
List<String> receivers = new ArrayList<String>();
receivers.add("收件人邮箱1");
receivers.add("收件人邮箱2"); // 附件
String fileName1 = "附件路径1";
File file1 = new File(fileName1);
String fileName2 = "附件路径2";
File file2 = new File(fileName2);
List<File> fileList = new ArrayList<File>();
fileList.add(file1);
fileList.add(file2); // 执行发送
new SendMail().sendEmail(title, htmlContent, receivers, fileList);
} }

代码:

package com.test;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication; /**
* 通过账号密码进行身份验证
*/
public class MailAuthenticator extends Authenticator {
private String userName;
private String password; public String getUserName() {
return userName;
} public void setUserName(String userName) {
this.userName = userName;
} public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password;
} @Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
} public MailAuthenticator(String username, String password) {
this.userName = username;
this.password = password;
}
}

最新文章

  1. Schedule 学习
  2. OAF_文件系列6_实现OAF导出XML文件javax.xml.parsers/transformer(案例)
  3. 2015-2016-2 《Java程序设计》教学进程
  4. [转]FastJSON通过SerializeFilter定制序列化
  5. 最大似然估计(MLE)和最大后验概率(MAP)
  6. hdu 1242 dfs/bfs
  7. hdu1547之BFS
  8. 谁在唱衰PC?说出你的理由
  9. 创建兼容的XHR对象
  10. OC语法4——自定义构造方法,description方法
  11. JavaScript 初识Promise 对象
  12. CSS3 基础(1)——选择器详解
  13. Python内置函数(56)——locals
  14. 【一天一道LeetCode】#69. Sqrt(x)
  15. 【DeepLearning】优化算法:SGD、GD、mini-batch GD、Moment、RMSprob、Adam
  16. Shell编程中while与for的区别及用法详解【转】
  17. 特征选取1-from sklearn.feature_selection import SelectKBest
  18. ELF文件解析(二):ELF header详解
  19. google test框架与eclipse插件
  20. 提高VS2010运行速度的技巧

热门文章

  1. 读书笔记--SQL必知必会04--过滤数据
  2. Thread Safety线程安全
  3. RAR和ZIP:压缩大战真相
  4. Linux内核源代码的结构(转)
  5. php中echo、print、print_r、printf的返回值
  6. 【HDOJ】2102 A计划
  7. Ext4.1 Grid 分页查询
  8. Oracle游标
  9. JS日期显示格式 yyyy-MM-dd hh:mm:ss
  10. 笔记:I/O流-字符集
  11. NetSarang软件中nssock2.dll模块被植入恶意代码技术分析与防护方案
  12. HttpClient学习--HttpClient的POST请求过程源码解读
  13. 学习MySQL过程中的随笔一
  14. ogg BR – BOUNDED RECOVERY 测试案例
  15. Java正则表达式初探(一)
  16. [文摘]那些一心想要离开 BAT 的人,后来怎么样了?
  17. Linux性能测试分析命令_vmstat
  18. openvas开放式漏洞评估系统
  19. Java界面编程—API
  20. NO.5:自学python之路------标准库,正则表达式