栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

发送QQ邮件

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

发送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 {
    
    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);
    }

    
    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);
    }

    
    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 {
    
    private String host;

    
    private Integer port;

    
    private Boolean auth = true;

    
    private String from;

    
    private String user;

    
    private String pass = "授权码" ;
  
    
    private String toAddress;
    
    private String subject;
    
    private String content;

    
    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());
    }
}

运行结果:

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/821559.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号