发送QQ邮件

一、工具类

package com.thk.utils;

import com.thk.domain.MailAccounts;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.Date;
import java.util.Properties;


public class MailSendUtils {
    /**
     * 邮箱发送
     *
     * @param mailAccounts
     * @throws Exception
     */
    public void send(MailAccounts mailAccounts) throws Exception {
        Message message = getMessage(mailAccounts);
        // MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象
        Multipart multipart = new MimeMultipart();
        // 创建一个包含HTML内容的MimeBodyPart
        BodyPart htmlOrTest = new MimeBodyPart();
        if (mailAccounts.getIsHtml()) {
            // 设置HTML内容
            htmlOrTest.setContent(mailAccounts.getContent(), "text/html; charset=utf-8");
        } else {
            htmlOrTest.setText(mailAccounts.getContent());
        }
        // 添加发送内容
        multipart.addBodyPart(htmlOrTest);
        if (mailAccounts.getFileUploadNames() != null) {
            // 添加附件
            for (String fileName : mailAccounts.getFileUploadNames()) {
                addEnclosure(multipart, fileName);
            }
        }
        // 将MiniMultipart对象设置为邮件内容
        message.setContent(multipart);
        Transport.send(message);
    }

    /**
     * 添加附件
     *
     * @param multipart
     * @param fileName  附件所在的地址
     * @throws Exception
     */
    private static void addEnclosure(Multipart multipart, String fileName) throws Exception {
        BodyPart adjunct = new MimeBodyPart();
        FileDataSource fileDataSource = new FileDataSource(fileName);
        adjunct.setDataHandler(new DataHandler(new URL(fileName)));
        adjunct.setFileName(changeEncode(fileDataSource.getName()));
        multipart.addBodyPart(adjunct);
    }

    /**
     * 进行base64加密,防止中文乱码
     */
    public static String changeEncode(String str) {
        try {
            str = MimeUtility.encodeText(new String(str.getBytes(), "UTF-8"),
                    "UTF-8", "B"); // "B"代表Base64
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return str;
    }

    private static Message getMessage(MailAccounts mailAccounts) throws Exception {
        final Properties properties = System.getProperties();
        properties.setProperty("mail.smtp.host", mailAccounts.getHost());
        properties.setProperty("mail.smtp.auth", mailAccounts.getAuth().toString());
        properties.setProperty("mail.smtp.user", mailAccounts.getFrom());
        properties.setProperty("mail.smtp.pass", mailAccounts.getPass());
        properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");  //使用JSSE的SSL socketfactory来取代默认的socketfactory
        properties.put("mail.smtp.socketFactory.fallback", "false");  // 只处理SSL的连接,对于非SSL的连接不做处理
        properties.put("mail.smtp.port", mailAccounts.getPort());
        properties.put("mail.smtp.socketFactory.port", mailAccounts.getPort());

        // 根据邮件会话属性和密码验证器构造一个发送邮件的session
        Session session = Session.getInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(properties.getProperty("mail.smtp.user"), properties.getProperty("mail.smtp.pass"));
            }
        });
        session.setDebug(true);
        Message message = new MimeMessage(session);
        //消息发送的主题
        message.setSubject(mailAccounts.getSubject());
        //消息的发送者
        message.setFrom(new InternetAddress(properties.getProperty("mail.smtp.user"), mailAccounts.getPersonal()));
        if (mailAccounts.getTo().length <= 0) {
            throw new Exception("收件人不能为空!!");
        }
        for (String strAdd : mailAccounts.getTo()) {
            // 创建邮件的接收者地址,并设置到邮件消息中
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(strAdd));
        }
        // 消息发送的时间
        message.setSentDate(new Date());
        return message;
    }

}

二、实体类

package com.thk.domain;

import lombok.*;


@Data
@AllArgsConstructor
@NoArgsConstructor
public class MailAccounts {
    /**
     * 邮箱地址,就是邮箱服务器的地址,在获取授权码那个页面可以获取到
     * <p>
     * 这里强烈注意:不用厂家的邮箱地址时不同的。
     * </p>
     */
    private String host;

    /**
     * 端口号,SSL模式
     */
    private Integer port;

    /***
     * 设置是否需要用户名密码验证,一般为true
     */
    private Boolean auth = true;

    /***
     * 发送方地址,获取授权码的邮箱
     */
    private String from;

    /**
     * 设置用户名,这个用户名必须是发送方的这个邮箱
     */
    private String user;

    /***
     * 授权码,
     */
    private String pass = "授权码" ;
  
    /**
     * 发送地址
     */
    private String toAddress;
    /**
     * 发送主题
     */
    private String subject;
    /**
     * 发送内容
     */
    private String content;

    /**
     * 是否为HTML格式,true:是,false:不是
     */
    private Boolean isHtml = false;

    /**
     * 发送者名称
     */
    private String personal;

    /**
     * 对象邮箱
     */
    private String[] to;

    /**
     * 附件路径信息集合
     */
    private String[] fileUploadNames = null;

    public void setTo(String... to) {
        this.to = to;
    }

    public void setFileUploadNames(String... fileUploadNames) {
        this.fileUploadNames = fileUploadNames;
    }

}

说明:实体类中的授权码需要到QQ邮箱当中获取

详见:https://jingyan.baidu.com/article/456c463b42f55e4b59314468.html

三、测试

代码:

public static void main(String[] args) {
    MailSendUtils mailSendUtils = new MailSendUtils();
    MailAccounts mailAccounts = new MailAccounts();
    mailAccounts.setHost("smtp.qq.com");//邮件地址
    mailAccounts.setPort(465);//端口号
    mailAccounts.setFrom("");//发送方地址
    mailAccounts.setSubject("测试发送邮件");//发送主题
    mailAccounts.setContent("测试发送邮件");//发送内容
    mailAccounts.setPersonal("测试发送邮件");//发送者名称
    mailAccounts.setTo("");//对象邮箱
    mailAccounts.setIsHtml(true);
    try {
        mailSendUtils.send(mailAccounts);
        System.out.println("发送成功!");
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("发送失败!"+e.getMessage());
    }
}

运行结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值