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;
    }
}
相关推荐
芊寻(嵌入式)16 分钟前
C转C++学习笔记--基础知识摘录总结
开发语言·c++·笔记·学习
WaaTong17 分钟前
《重学Java设计模式》之 原型模式
java·设计模式·原型模式
m0_7430484417 分钟前
初识Java EE和Spring Boot
java·java-ee
AskHarries19 分钟前
Java字节码增强库ByteBuddy
java·后端
一颗松鼠24 分钟前
JavaScript 闭包是什么?简单到看完就理解!
开发语言·前端·javascript·ecmascript
有梦想的咸鱼_26 分钟前
go实现并发安全hashtable 拉链法
开发语言·golang·哈希算法
海阔天空_201332 分钟前
Python pyautogui库:自动化操作的强大工具
运维·开发语言·python·青少年编程·自动化
天下皆白_唯我独黑39 分钟前
php 使用qrcode制作二维码图片
开发语言·php
小灰灰__39 分钟前
IDEA加载通义灵码插件及使用指南
java·ide·intellij-idea
夜雨翦春韭43 分钟前
Java中的动态代理
java·开发语言·aop·动态代理