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

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

废话不说进入正题:

  1. 1.

第一步

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

    <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4.7</version>
        </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<String> 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<String> 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//你的授权码。 不是邮箱的密码

如何开起你的授权码?自己百度
开授权

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

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

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

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

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值