博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
javax.mail用smtp服务器发送带附件的邮件
阅读量:6173 次
发布时间:2019-06-21

本文共 6108 字,大约阅读时间需要 20 分钟。

jar包:

javax.mail-1.5.5.jar

 

maven配置:

com.sun.mail
javax.mail
1.5.5

 

代码:

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
receivers, List
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
receivers, List
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
receivers = new ArrayList
(); receivers.add("收件人邮箱1"); receivers.add("收件人邮箱2"); // 附件 String fileName1 = "附件路径1"; File file1 = new File(fileName1); String fileName2 = "附件路径2"; File file2 = new File(fileName2); List
fileList = new ArrayList
(); 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;    }}

 

转载地址:http://optba.baihongyu.com/

你可能感兴趣的文章
[MySQL 5.6] 5.6新参数slave_rows_search_algorithms
查看>>
ESXi5.1嵌套KVM虚拟化环境支持配置
查看>>
爬虫的小技巧之–如何寻找爬虫入口
查看>>
JVM学习(二)垃圾收集器
查看>>
为hexo博客添加基于gitment评论功能
查看>>
java 库存 进销存 商户 多用户管理系统 SSM springmvc 项目源码
查看>>
Flutter - Drawer 抽屉视图与自定义header
查看>>
ERP系统的优势_库存管理软件开发
查看>>
如何内行地评价公链(一)从真正的不可能三角谈起
查看>>
BigDecimal 详解
查看>>
Shell实战之函数的高级用法
查看>>
NASA制做模拟系外行星环境 发现了热木星大气不透明的原因
查看>>
Slog67_后端框架Skynet之Makefile解读
查看>>
iOS ShareSDK桥接技术
查看>>
BAT面试须知:Java开发的招聘标准
查看>>
WeUI for 小程序–使用教程
查看>>
[vuex] unknown action type
查看>>
深入浅出 Java 并发编程 (1)
查看>>
【神器】可视化创建骨架屏
查看>>
数组左边减去右边数值的最大差值
查看>>