Java&&Mail

Java&&Mail


发送邮箱帮助类,亲测有效

pom依赖

  <dependency>
     <groupId>javax.mail</groupId>
     <artifactId>mail</artifactId>
     <version>1.4.7</version>
 </dependency>

示例代码


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.InputStream;
import java.security.GeneralSecurityException;
import java.util.Properties;

/**
 * 邮件帮助类
 * @Author jinyaoyu
 * @Date 2022/1/21 15:01
 **/
public class MailUtils {

    //发件人邮箱
    public static String send_email_account = "xxx@xx.com";
    //发件人密码,此处为授权码 获取参考: https://service.mail.qq.com/cgi-bin/help?subtype=1&id=28&no=1001256
    public static String send_email_pwd = "smaifdsietmmgdhd";
    //smtp host 参考: https://service.mail.qq.com/cgi-bin/help?subtype=1&&id=28&&no=371
    public static String email_host = "smtp.qq.com";
    //smtp port
    public static String email_port = "465";

    public static void main(String[] args) {
        sendMsgWithFile("xuwj@linkstec.com","标题测试","内容测试",null,null);
    }

    /**
     * 发送邮件,带附件的那种
     *
     * @param to          邮件收件人地址
     * @param subject     邮件标题
     * @param text        内容
     * @param affixName   附件标题
     * @param inputStream 附件输入流
     */
    public static void sendMsgWithFile(String to, String subject, String text, String affixName, InputStream inputStream) {
        Session session = assembleSession();
        Message msg = new MimeMessage(session);
        try {
            msg.setFrom(new InternetAddress(send_email_account));
            msg.setSubject(subject);
            msg.setRecipients(Message.RecipientType.TO, acceptAddressList(to));
            MimeBodyPart contentPart = (MimeBodyPart) createContent(text, inputStream, affixName);//参数为正文内容和附件流
            MimeMultipart mime = new MimeMultipart("mixed");
            mime.addBodyPart(contentPart);
            msg.setContent(mime);
            Transport.send(msg);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送邮件
     *
     * @param to      邮件收件人地址
     * @param subject 邮件标题
     * @param text    内容
     */
    public void sendMsg(String to, String subject, String text) {
        this.sendMsgWithFile(to, subject, text, null, null);
    }

    /**
     * 创建邮件的接收者地址,并设置到邮件消息中
     *
     * @param acceptAddress 邮件地址列表
     * @return 地址数组
     */
    public static Address[] acceptAddressList(String... acceptAddress) {
        Address[] tos = null;
        try {
            tos = new InternetAddress[acceptAddress.length];
            for (int i = 0; i < acceptAddress.length; i++) {
                tos[i] = new InternetAddress(acceptAddress[i]);
            }
        } catch (AddressException e) {
            e.printStackTrace();
        }
        return tos;
    }

    /**
     * 登录邮件服务器,返回session
     *
     * @return 登录session
     */
    public static Session assembleSession() {
        Session session = null;
        Properties props = new Properties();
        props.setProperty("mail.smtp.auth", "true");
        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.smtp.port", email_port);
        props.setProperty("mail.smtp.host", email_host);//邮件服务器
        //开启安全协议
        MailSSLSocketFactory sf = null;
        try {
            sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
        } catch (GeneralSecurityException e1) {
            e1.printStackTrace();
        }
        props.put("mail.smtp.ssl.socketFactory", sf);
        props.put("mail.smtp.ssl.enable", "true");
        session = Session.getInstance(props, new MyAuthenticator(send_email_account, send_email_pwd));
        return session;
    }

    /**
     * 创建邮件内容
     *
     * @param content     邮件正文
     * @param inputStream 邮件附件输入流
     * @param affixName   文件名称
     * @return
     */
    static Part createContent(String content, InputStream inputStream, String affixName) {
        MimeBodyPart contentPart = null;
        try {
            contentPart = new MimeBodyPart();
            MimeMultipart contentMultipart = new MimeMultipart("related");
            MimeBodyPart htmlPart = new MimeBodyPart();
            htmlPart.setContent(content, "text/html;charset=utf-8");
            contentMultipart.addBodyPart(htmlPart);
            if (inputStream != null && affixName != null) {
                //附件部分
                MimeBodyPart excelBodyPart = new MimeBodyPart();
                DataSource dataSource = new ByteArrayDataSource(inputStream, "application/excel");
                DataHandler dataHandler = new DataHandler(dataSource);
                excelBodyPart.setDataHandler(dataHandler);
                excelBodyPart.setFileName(MimeUtility.encodeText(affixName));
                contentMultipart.addBodyPart(excelBodyPart);
            }
            contentPart.setContent(contentMultipart);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return contentPart;
    }

    //用户名密码验证,需要实现抽象类Authenticator的抽象方法PasswordAuthentication
    static class MyAuthenticator extends Authenticator {
        String u = null;
        String p = null;

        public MyAuthenticator(String u, String p) {
            this.u = u;
            this.p = p;
        }

        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(u, p);
        }
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

金肴羽

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值