Java 腾讯邮箱发送邮件带附件(以文件流的形式)

邮箱实体类

package com.unionx.core.util.email;
import lombok.Data;
import javax.mail.internet.InternetAddress;

@Data
public class EmailMailInfo {
    //邮箱服务器 如smtp.163.com
    private String host ;
    //用户邮箱 如**@163
    private String formName ;
    //用户授权码 不是用户名密码 可以自行查看相关邮件服务器怎么查看
    private String formPassword ;
    //消息回复邮箱
    private String replayAddress ;
    //发送地址
    private String toAddress ;
    //发送主题
    private String subject ;
    //发送内容
    private String content ;
    //端口号
    private String port;
    //多人邮件
    private InternetAddress[] emailMany;
    //附件地址
    private String filePath;
    //附件名称
    private String fileName;

    public String getPort() {
        return port;
    }

    public void setPort(String port) {
        this.port = port;
    }

    public String getHost() {
        return host;
    }
    public void setHost(String host) {
        this.host = host;
    }
    public String getFormName() {
        return formName;
    }
    public void setFormName(String formName) {
        this.formName = formName;
    }
    public String getFormPassword() {
        return formPassword;
    }
    public void setFormPassword(String formPassword) {
        this.formPassword = formPassword;
    }
    public String getReplayAddress() {
        return replayAddress;
    }
    public void setReplayAddress(String replayAddress) {
        this.replayAddress = replayAddress;
    }
    public String getToAddress() {
        return toAddress;
    }
    public void setToAddress(String toAddress) {
        this.toAddress = toAddress;
    }
    public String getSubject() {
        return subject;
    }
    public void setSubject(String subject) {
        this.subject = subject;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }

    public InternetAddress[] getEmailMany() {
        return emailMany;
    }

    public void setEmailMany(InternetAddress[] emailMany) {
        this.emailMany = emailMany;
    }
}

组装业务数据

	public static void sendWord(ByteArrayOutputStream baos, List<String> emailList) throws Exception {
		ByteArrayInputStream InputStream = new ByteArrayInputStream(baos.toByteArray());
		EmailMailInfo info = new EmailMailInfo();
		info.setFileName("文件名字.docx");
		info.setSubject("邮件标题");
		info.setContent("邮件内容");
		info.setEmailMany(addressMails(emailList));
		EmailSendUtil.sendHtmlMailAndFile(info, InputStream);
	}
	/**
	 * 多个账号邮箱的公共方法
	 * @param emailList
	 * @return
	 */
	private static InternetAddress[] addressMails(List emailList) throws AddressException {
		List list = new ArrayList();//不能使用string类型的类型,这样只能发送一个收件人
		//多个接收账号
		for (int i = 0; i < emailList.size(); i++) {
			list.add(new InternetAddress(emailList.get(i).toString()));
		}
		return (InternetAddress[]) list.toArray(new InternetAddress[list.size()]);
	}

发送邮箱的工具类

package com.unionx.core.util.email;

import com.sun.mail.util.MailSSLSocketFactory;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.util.ByteArrayDataSource;
import java.io.ByteArrayInputStream;
import java.security.GeneralSecurityException;
import java.util.Date;
import java.util.Properties;


public class EmailSendUtil {
    private final static String host = "smtp.exmail.qq.com"; //腾讯企业邮的服务器
    private final static String formName = "";//发件人邮箱
    private final static String password = ""; //发件人授权码
    private final static String replayAddress = ""; //发件人邮箱
    // private final static String port = "465"; //邮箱端口
    private final static String port = "587"; //邮箱端口

    private static Message getMessage(EmailMailInfo info) throws Exception{
        final Properties p = System.getProperties() ;
        p.setProperty("mail.smtp.host", info.getHost());
        p.setProperty("mail.smtp.auth", "true");
        p.setProperty("mail.smtp.user", info.getFormName());
        p.setProperty("mail.smtp.pass", info.getFormPassword());
        p.setProperty("mail.smtp.port", info.getPort());//设置端口
        p.setProperty("mail.transport.protocol", "smtp");//
        p.setProperty("mail.smtp.ssl.protocols", "TLSv1.2");

        //开启安全协议 QQ邮箱需要下面这段代码,163邮箱不需要
         MailSSLSocketFactory sf = null;
        try {
            sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            p.put("mail.smtp.ssl.enable", "true");
            p.put("mail.smtp.ssl.socketFactory", sf);
        } catch (GeneralSecurityException e1) {
            e1.printStackTrace();
        }
        // 根据邮件会话属性和密码验证器构造一个发送邮件的session
        Session session = Session.getDefaultInstance(p, new Authenticator(){
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(p.getProperty("mail.smtp.user"),p.getProperty("mail.smtp.pass"));
            }
        });
        session.setDebug(false);
        Message message = new MimeMessage(session);
        //消息发送的主题
        message.setSubject(info.getSubject());
        //接受消息的人
        //message.setReplyTo(InternetAddress.parse(info.getReplayAddress()));
        //消息的发送者
        message.setFrom(new InternetAddress(p.getProperty("mail.smtp.user"),"邮箱标题"));
        // 创建邮件的接收者地址,并设置到邮件消息中
        //单人接收邮件
        //message.setRecipient(Message.RecipientType.TO,new InternetAddress(info.getToAddress()));
        //多人接收邮件
        message.setRecipients(Message.RecipientType.TO, info.getEmailMany());
        // 消息发送的时间
        message.setSentDate(new Date());
        return message ;
    }
    
    /**
      * @Description: 发送带附件的邮件
      * @author: ly
      * @param info
      * @param inputStream
      * @return void
      **/
    public static void sendHtmlMailAndFile(EmailMailInfo info, ByteArrayInputStream inputStream) throws Exception {
        info.setHost(host);
        info.setFormName(formName);
        info.setFormPassword(password);   //网易邮箱的授权码~不一定是密码
        info.setReplayAddress(replayAddress);
        info.setPort(port);
        Message message = getMessage(info);
        // MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象
        Multipart mainPart = new MimeMultipart();
        //创建附件
        MimeBodyPart contentPart=(MimeBodyPart) createContent(info,inputStream);//参数为正文内容和附件流
        mainPart.addBodyPart(contentPart);
        // 将MiniMultipart对象设置为邮件内容
        message.setContent(mainPart);
        Transport.send(message);
    }

    static Part createContent(EmailMailInfo info,ByteArrayInputStream inputstream){
        MimeBodyPart contentPart=null;
        try {
            contentPart=new MimeBodyPart();
            MimeMultipart contentMultipart=new MimeMultipart("related");
            MimeBodyPart htmlPart=new MimeBodyPart();
            htmlPart.setContent(info.getContent(), "text/html;charset=gbk");
            contentMultipart.addBodyPart(htmlPart);
            //附件部分
            MimeBodyPart excelBodyPart=new MimeBodyPart();
            DataSource dataSource=new ByteArrayDataSource(inputstream, "application/msword");
            DataHandler dataHandler=new DataHandler(dataSource);
            excelBodyPart.setDataHandler(dataHandler);
            excelBodyPart.setFileName(MimeUtility.encodeText(info.getFileName()));
            contentMultipart.addBodyPart(excelBodyPart);
            contentPart.setContent(contentMultipart);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return contentPart;
    }
}
相关推荐
IT女孩儿7 分钟前
JavaScript--WebAPI查缺补漏(二)
开发语言·前端·javascript·html·ecmascript
m0_748238928 分钟前
webgis入门实战案例——智慧校园
开发语言·ios·swift
醒了就刷牙13 分钟前
黑马Java面试教程_P9_MySQL
java·mysql·面试
m0_7482336420 分钟前
SQL数组常用函数记录(Map篇)
java·数据库·sql
Clockwiseee21 分钟前
PHP伪协议总结
android·开发语言·php
小灰灰搞电子23 分钟前
Qt实现Android的图案密码(图形解锁)源码分享
开发语言·qt
编程爱好者熊浪1 小时前
JAVA HTTP压缩数据
java
吴冰_hogan1 小时前
JVM(Java虚拟机)的组成部分详解
java·开发语言·jvm
白宇横流学长2 小时前
基于java出租车计价器设计与实现【源码+文档+部署讲解】
java·开发语言
数据小爬虫@4 小时前
Java爬虫实战:深度解析Lazada商品详情
java·开发语言