利用Java的JavaMail发送邮件:企业邮箱版和个人邮箱客端版

本文链接: http://blog.csdn.net/qq_35257397/article/details/79004987

废话不说进入正题:

    1.

第一步

项目基于maven 搭建。引入pom.xml

    <dependency>
            <groupId>javax.mailgroupId>
            <artifactId>mailartifactId>
            <version>1.4.7version>
        dependency>

第二步

创建邮箱实体类封装数据。

@Data//get set 插件

public class MailVO implements Serializable {

    private static final long serialVersionUID = 4280650483975256784L;
    // 邮件发送者的标示
    private String key;
    // 登陆邮件发送服务器的用户名和密码
    private String mailAccount;
    private String mailPassword;
    //收件人名字
    private String senderAlias;
    // 邮件接收者的地址数组
    private List receiveAddressArray;

    // 邮件主题
    private String subject;
    // 邮件的文本内容
    private String content;
    // 邮件附件的文件名
    private String[] attachFileNames;
}

实现的代码

/**
 * Created by why on 2017/7/28.
 */
public class MailServiceImp implements MailService {

    @Resource(name = "taskExecutor")
    TaskExecutor taskExecutor;//注入Spring封装的异步执行器

    private Log log = LogFactory.getLog(getClass());


    public void sendEmail(MailVO mail){
        Properties emailProperty = new Properties();
        try {
            InputStream resourceAsStream = MailServiceImp.class.getClassLoader().getResourceAsStream("application.properties");
            emailProperty.load(new BufferedInputStream(resourceAsStream));
        } catch (IOException e) {
            e.printStackTrace();
        }
        Properties sendProperty = new Properties();
        mail.setMailAccount(emailProperty.getProperty("mail.account"));
        mail.setMailPassword(emailProperty.getProperty("mail.password"));
        mail.setSenderAlias(emailProperty.getProperty("mail.alias"));
        sendProperty.setProperty("mail.transport.protocol",emailProperty.getProperty("mail.transport.protocol"));// 使用的协议(JavaMail规范要求)
        sendProperty.setProperty("mail.smtp.host",emailProperty.getProperty("mail.smtp.host"));// 发件人的邮箱的 SMTP 服务器地址
        sendProperty.setProperty("mail.smtp.auth",emailProperty.getProperty("mail.smtp.auth"));
        // 开启SSL加密,否则会失败



        try {
        MailSSLSocketFactory sf =new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        sendProperty.put("mail.smtp.ssl.enable", "true");
        sendProperty.put("mail.smtp.ssl.socketFactory", sf);

        Session session = Session.getDefaultInstance(sendProperty);
        session.setDebug(true);  //设置为debug模式看日志
//        sendMailByAsynchronousMode(session,mail);

            sendMailBySynchronizationMode(session,mail);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void sendMailByAsynchronousMode(Session session,MailVO mail){

        taskExecutor.execute(new Runnable(){
            @Override
            public void run(){
                try {

                    sendMailBySynchronizationMode(session,mail);
                } catch (Exception e) {
                    log.info(e);
                }
            }
        });
    }

    private void sendMailBySynchronizationMode(Session session,MailVO mail) throws IOException,MessagingException {


        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(mail.getMailAccount(),mail.getKey()));
        List recipients = mail.getReceiveAddressArray();

            final int num = recipients.size();
            InternetAddress[] addresses = new InternetAddress[num];
            for (int i = 0; i < num; i++) {
                addresses[i] = new InternetAddress(recipients.get(i));
            }
            message.setRecipients(Message.RecipientType.TO, addresses);

        message.setSubject(mail.getSubject(), "UTF-8");
        message.setContent(mail.getContent(),"text/html;charset=UTF-8");
        message.setSentDate(new Date());
        message.saveChanges();

        Transport transport = session.getTransport();
        transport.connect(mail.getMailAccount(),mail.getMailPassword());


        // 6. 发送邮件, 发到所有的收件地址, message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人
        transport.sendMessage(message, message.getAllRecipients());
        // 7. 关闭连接
        transport.close();


    }



}

代码中注释的
@Resource(name = “taskExecutor”)
TaskExecutor taskExecutor;//注入Spring封装的异步执行器
是多线程发送邮箱的。有兴趣个人

最后一部配置application.properties

#邮件发送
mail.transport.protocol=smtp
mail.account=XXXX@163.com//填你的账号
mail.password=XXX//你的授权码。 不是邮箱的密码
mail.smtp.host= smtp.qiye.163.com
#mail.smtp.host=smtp.qq.com
mail.smtp.auth=true

说明一下配置文件

mail.password=XXX//你的授权码。 不是邮箱的密码

如何开起你的授权码?自己百度
利用Java的JavaMail发送邮件:企业邮箱版和个人邮箱客端版_第1张图片

最最罪重要的,这里很坑爹

host 通道个人邮箱和企业邮箱通道不同

下面是163的
个人邮箱:smtp.163.com
企业邮箱:smtp.qiye.163.com

希望有帮助到你哟。有什么不清楚的请留言哟。

你可能感兴趣的:(实战记录)