javax.mail发送邮件工具类

maven引入配置

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

工具类代码

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

/**
 * Java发送邮件工具类
 * 
 * @author wangzhongxing
 * @version $Id: SendMailUtil.java, v 0.1 2018年10月24日 下午3:29 wangzhongxing Exp $
 */
public class SendMailUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(SendMailUtil.class);

    /**
     * 发送带附件的邮件
     * @param mailHost SMTP服务的服务器地址,在邮箱账号设置里能看到
     * @param protocol 邮件发送协议,取值为:smtp
     * @param fromAddress 邮件发送方邮箱账号,需要发送账号开通POP3/SMTP/IMAP服务才能发送邮件
     * @param password 开启POP3/SMTP/IMAP服务时设置的邮箱授权码
     * @param recipientAddress 邮件接收方账号
     * @param subject 邮件主题
     * @param content 邮件正文
     * @param attachFiles 附件
     * @return
     */
    public static boolean sendAttachMail(String mailHost, String protocol, String fromAddress,
                                         String password, String recipientAddress, String subject,
                                         String content, List<DataSource> attachFiles) {
        Properties prop = new Properties();
        prop.setProperty("mail.host", mailHost);
        prop.setProperty("mail.transport.protocol", protocol);
        prop.setProperty("mail.smtp.auth", "true");
        //使用JavaMail发送邮件的5个步骤
        //1、创建session
        Session session = Session.getInstance(prop);
        //开启Session的debug模式,这样就可以查看到程序发送Email的运行状态
        session.setDebug(true);
        Transport ts = null;
        try {
            //2、通过session得到transport对象
            ts = session.getTransport();
            //3、连上邮件服务器
            ts.connect(mailHost, fromAddress, password);
            //4、创建邮件
            Message message = createAttachMail(session, fromAddress, recipientAddress, subject,
                content, attachFiles);
            //5、发送邮件
            Thread.currentThread().setContextClassLoader(ts.getClass().getClassLoader());
            ts.sendMessage(message, message.getAllRecipients());
        } catch (MessagingException e) {
            LOGGER.error("SendMailUtil.sendAttachMail MessagingException!subject={0}", subject, e);

            return false;
        } catch (Exception e) {
            LOGGER.error("SendMailUtil.sendAttachMail Exception!subject={0}", subject, e);

            return false;
        } finally {
            try {
                ts.close();
            } catch (MessagingException e) {
                LOGGER.error("SendMailUtil.sendAttachMail finally MessagingException!subject={0}",
                    subject, e);
            }
        }

        return true;
    }

    /**
     * 创建带附件的邮件正文
     *
     * @param session
     * @return
     * @throws Exception
     */
    public static MimeMessage createAttachMail(Session session, String fromAddress,
                                               String recipientAddress, String subject,
                                               String content,
                                               List<DataSource> ds) throws Exception {
        MimeMessage message = new MimeMessage(session);

        //设置邮件的基本信息
        //发件人
        message.setFrom(new InternetAddress(fromAddress));
        //收件人
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipientAddress));
        //邮件标题
        message.setSubject(subject);
        //创建邮件正文,为了避免邮件正文中文乱码问题,需要使用charset=UTF-8指明字符编码
        MimeBodyPart text = new MimeBodyPart();
        text.setContent(content, "text/html;charset=UTF-8");

        //创建容器描述数据关系
        MimeMultipart mp = new MimeMultipart();
        mp.addBodyPart(text);
        mp.setSubType("mixed");

        //创建邮件附件
        if (!CollectionUtils.isEmpty(ds)) {
            for (DataSource dataSource : ds) {
                DataHandler dh = new DataHandler(dataSource);
                MimeBodyPart attach = new MimeBodyPart();
                attach.setDataHandler(dh);
                attach.setFileName(MimeUtility.encodeText(dh.getName()));
                mp.addBodyPart(attach);
            }
        }

        message.setContent(mp);
        message.saveChanges();

        //返回生成的邮件
        return message;
    }

    public static void main(String[] args) {
        // 邮箱服务器地址,不同邮箱服务商该地址不一样
        String mailHost = "smtp.163.com";
        String protocol = "smtp";
        // 邮件发送方邮箱地址
        String fromAddress = "xxxxx@163.com";
        // 邮件发送方邮箱授权码
        String password = "xxxxxx";
        // 邮件接收方邮箱地址
        String recipientAddress = "xxxxxx@qq.com";
        String subject = "JavaMail邮件发送测试";
        String content = "使用JavaMail创建的带附件的邮件";
        List<DataSource> dataSources = new ArrayList<>();
        FileDataSource attachFile = new FileDataSource(
            "/Users/wangzhongxing/CodeFormatter.xml");
        dataSources.add(attachFile);
        boolean result = sendAttachMail(mailHost, protocol, fromAddress, password, recipientAddress, subject, content, dataSources);

        System.out.println(result);
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值