java发送 邮件工具类

本文展示了如何使用JavaMail API发送带有附件的电子邮件。通过EmailConfigModel配置邮件服务器参数,创建并设置MimeMessage,添加附件,然后通过SMTP发送邮件。代码中包含了SSL配置、邮件内容设置及文本和HTML内容的混合发送。
摘要由CSDN通过智能技术生成

pom 文件

    <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-email</artifactId>
            <version>1.5</version>
        </dependency>

1,工具类

@Data
public class EmailConfigModel {

    /**
     * 启用, 0:启用, 1:弃用。
     */
    private Integer enable;

    /**
     * 邮箱。
     */
    private String emailBox;

    /**
     * 邮箱密码。
     */
    private String passWord;

    /**
     * 端口。
     */
    private String port;

    /**
     * 邮件服务器地址。
     */
    private String serverUrl;

    /**
     * ssl启用, 0:启用, 1:弃用。
     */
    private Integer enSsl;
}

2,附件

@Data

public class AFile {
    /**
     * 文件名称
     */
    private String name;

    /**
     * 文件连接
     */
    private String url;

}

3,工具类

@Log4j
public class EmailUtil {

    private EmailUtil() {
    }

    private static final String AINAME = "AI";
    private static final int SOCKET_TIMEOUT_MS = 10000;

    static {
        System.setProperty("mail.mime.splitlongparameters", "false");
        System.setProperty("mail.mime.charset", "utf-8");
    }

    public static synchronized void deliverWithMime(EmailConfigModel emailConfigModel,
                                                    String subject,
                                                    String msg,
                                                    String toMail,
                                                    List<AFile> attachmentList,
                                                    List<AFile> detailPicList)
            throws MessagingException, GeneralSecurityException {
        Properties prop = new Properties();
        prop.setProperty("mail.host", emailConfigModel.getServerUrl());
        prop.setProperty("mail.transport.protocol", "smtp");
        prop.setProperty("mail.smtp.port", String.valueOf(emailConfigModel.getPort()));
        prop.setProperty("mail.mime.splitlongparameters", "false");
        prop.setProperty("mail.smtp.auth", "true");
        if (emailConfigModel.getEnSsl() == 0) {
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            prop.put("mail.smtp.ssl.enable", "true");
            prop.put("mail.smtp.ssl.socketFactory", sf);
        }
        //使用JavaMail发送邮件的5个步骤
        //1、创建session
        Session session = Session.getInstance(prop, new Authenticator() {
            @Override
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(emailConfigModel.getEmailBox(), emailConfigModel.getPassWord()); //发件人邮件用户名、密码
            }
        });
        //开启Session的debug模式,这样就可以查看到程序发送Email的运行状态
        session.setDebug(false);
        //2、通过session得到transport对象
        Transport ts = session.getTransport();
        //3、使用邮箱的用户名和密码连上邮件服务器,发送邮件时,发件人需要提交邮箱的用户名和密码给smtp服务器,用户名和密码都通过验证之后才能够正常发送邮件给收件人。
        ts.connect(emailConfigModel.getEmailBox(), emailConfigModel.getPassWord());
        //4、创建邮件
        MimeMessage message = new MimeMessage(session);
        //4.1、设置邮件的基本信息
        //4.2、发件人
        String nick = "";
        try {
            nick = MimeUtility.encodeText("ai");
        } catch (UnsupportedEncodingException e) {
            System.out.println("编码失败:" + "ai" + e);
        }
        message.setFrom(new InternetAddress(nick + "<" + emailConfigModel.getEmailBox() + ">"));
        //4.3、收件人
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(toMail));
        //4.4、邮件标题
        message.setSubject(subject);
        //4.5、创建邮件附件
        MimeMultipart mp = new MimeMultipart();
        FileDataSource filedatasource;
        MimeBodyPart filePart;
        List<AFile> attachments = new ArrayList<>();
        if (attachmentList != null) {
            attachments.addAll(attachmentList);
        }
        if (detailPicList != null) {
            attachments.addAll(detailPicList);
        }
         for (AFile attachment : attachments) {
            File file = new File(attachment.getUrl());
            if (file.exists()) {
                filePart = new MimeBodyPart();
                filedatasource = new FileDataSource(file);
                filePart.setDataHandler(new DataHandler(filedatasource));
                try {
                    filePart.setFileName(MimeUtility.encodeText(attachment.getName()));
                } catch (Exception e) {
                    log.error("设置文件名失败:" + file.getName(), e);
                }
                mp.addBodyPart(filePart);
            }
        }

        //4.6、写入文本内容
        BodyPart htmlPart = new MimeBodyPart();
        htmlPart.setContent(msg, "text/html; charset=utf-8");
        mp.addBodyPart(htmlPart);
        //4.7、组合内容
        message.setContent(mp);
        message.saveChanges();
        //5、发送邮件
        ts.sendMessage(message, message.getAllRecipients());
        ts.close();
    }

    private static Email buildEmailInstance(EmailConfigModel emailConfigModel) throws EmailException {
        Email emailInstance = new SimpleEmail();
        emailInstance.setDebug(false);
        emailInstance.setHostName(emailConfigModel.getServerUrl());
        if (emailConfigModel.getEnSsl() == 0) {
            //前端传值错误,当ssl = 0时是打开ssl
            emailInstance.setSslSmtpPort(emailConfigModel.getPort());
        } else {
            emailInstance.setSmtpPort(Integer.parseInt(emailConfigModel.getPort()));
        }
        emailInstance.setAuthenticator(
                new DefaultAuthenticator(emailConfigModel.getEmailBox(), emailConfigModel.getPassWord()));
        emailInstance.setSSLOnConnect(emailConfigModel.getEnSsl() == 0);
        emailInstance.setFrom(emailConfigModel.getEmailBox(), AINAME);
        emailInstance.setSocketTimeout(SOCKET_TIMEOUT_MS);
        return emailInstance;
    }

    public static void sendSimpleEmail(EmailConfigModel emailConfigModel, String subject, String msg, String toMail)
            throws EmailException {
        String newMsg = msg.replace("#$]", "\r\n");
        Email email = buildEmailInstance(emailConfigModel);
        email.setSubject(subject).addTo(toMail).setMsg(newMsg).send();
    }

    public static void sendSimpleEmailByHtml(EmailConfigModel emailConfigModel, String subject, String msg, String toMail)
            throws EmailException {
        Email email = buildEmailInstance(emailConfigModel);
        email.setContent(msg, "text/html;charset=utf-8");
        email.setSubject(subject).addTo(toMail).send();
    }


    public static void main(String[] args) throws GeneralSecurityException, MessagingException {
        EmailConfigModel emailConfigModel = new EmailConfigModel();
        emailConfigModel.setServerUrl("smtp.163.com");
        emailConfigModel.setEmailBox("xxxxxx@163.com");
        emailConfigModel.setPort("25");
        emailConfigModel.setPassWord("安全码");
        emailConfigModel.setEnSsl(1);
        emailConfigModel.setEnable(0);
        EmailUtil.deliverWithMime(emailConfigModel, "测试邮箱", "你好,请忽略", "xxxxx@qq.com", null, null);


    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

大道至简@EveryDay

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

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

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

打赏作者

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

抵扣说明:

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

余额充值