zoukankan      html  css  js  c++  java
  • Java + 腾讯企业邮箱 + javamail + SSL 发送邮件

    说实话腾讯的企业邮箱真心不错!

    腾讯企业邮箱官网:http://exmail.qq.com/login/

    新用户注册:http://exmail.qq.com/onlinesell/intro

    点击开通

    你跟着步骤走就行了,没啥难的,如果你没有域名,你就去买一个呗,也花不了多少钱的。

    注册成功后,是这个页面,并且会有一个弹窗告诉你一些信息

    现在你点击添加成员,因为你不添加成员的话你是无法发送邮件的。

    完成后是这样

    然后你打开腾讯企业邮箱登录界面,输入你刚才增加的成员邮箱的:登录名 + 密码,进去后是一个类似于普通QQ邮箱的界面

    到这里邮箱部分就解决了,哦还有,腾讯会自动给你发一个邮件,

    点开后是这个,

    以前写过普通QQ邮箱的发送代码,我从没见过SSL,所以一开始全然不懂。。,但是上网查阅得知

    随着各个Mail服务器对于安全的重视,纷纷采用基于SSL的Mail登陆方式进行发送和接收电子邮件

    好了现在开始写代码。

    大家反映之前写的容易误导人,所以今天修改了这个文章一下2017-09-05

     有一个属性文件用来存储邮箱信息的

    email.properties,放在src路径下面
    e.account=账户名
    e.pass=密码
    e.host=smtp.exmail.qq.com
    e.port=465
    e.protocol=smtp

    下面是发送类:

    package mail.demo;
    
    import java.io.IOException;
    import java.io.UnsupportedEncodingException;
    import java.security.GeneralSecurityException;
    import java.util.Date;
    import java.util.Properties;
    
    import javax.mail.Authenticator;
    import javax.mail.Message;
    import javax.mail.MessagingException;
    import javax.mail.Multipart;
    import javax.mail.PasswordAuthentication;
    import javax.mail.Session;
    import javax.mail.Transport;
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeBodyPart;
    import javax.mail.internet.MimeMessage;
    import javax.mail.internet.MimeMultipart;
    
    import org.springframework.core.io.support.PropertiesLoaderUtils;
    
    import com.sun.mail.util.MailSSLSocketFactory;
    
    public class SendEmailUtil {
    
        private static String account;    //登录用户名
        private static String pass;        //登录密码
        private static String host;        //服务器地址(邮件服务器)
        private static String port;        //端口
        private static String protocol; //协议
        
        static{
            Properties prop = new Properties();
    //        InputStream instream = ClassLoader.getSystemResourceAsStream("email.properties");//测试环境
            try {
    //            prop.load(instream);//测试环境
                prop = PropertiesLoaderUtils.loadAllProperties("email.properties");//生产环境
            } catch (IOException e) {
                System.out.println("加载属性文件失败");
            }
            account = prop.getProperty("e.account");
            pass = prop.getProperty("e.pass");
            host = prop.getProperty("e.host");
            port = prop.getProperty("e.port");
            protocol = prop.getProperty("e.protocol");
        }
        
        static class MyAuthenricator extends Authenticator{  
            String u = null;  
            String p = null;  
            public MyAuthenricator(String u,String p){  
                this.u=u;  
                this.p=p;  
            }  
            @Override  
            protected PasswordAuthentication getPasswordAuthentication() {  
                return new PasswordAuthentication(u,p);  
            }  
        }
        
        private String to;    //收件人
        private String subject;    //主题
        private String content;    //内容
        private String fileStr;    //附件路径
    
        public SendEmailUtil(String to, String subject, String content, String fileStr) {
            this.to = to;
            this.subject = subject;
            this.content = content;
            this.fileStr = fileStr;
        }
    
    
    
        public void send(){
            Properties prop = new Properties();
            //协议
            prop.setProperty("mail.transport.protocol", protocol);
            //服务器
            prop.setProperty("mail.smtp.host", host);
            //端口
            prop.setProperty("mail.smtp.port", port);
            //使用smtp身份验证
            prop.setProperty("mail.smtp.auth", "true");
            //使用SSL,企业邮箱必需!
            //开启安全协议
            MailSSLSocketFactory sf = null;
            try {
                sf = new MailSSLSocketFactory();
                sf.setTrustAllHosts(true);
            } catch (GeneralSecurityException e1) {
                e1.printStackTrace();
            }
            prop.put("mail.smtp.ssl.enable", "true");
            prop.put("mail.smtp.ssl.socketFactory", sf);
            
            Session session = Session.getDefaultInstance(prop, new MyAuthenricator(account, pass));
            session.setDebug(true);
            MimeMessage mimeMessage = new MimeMessage(session);
            try {
                //发件人
                mimeMessage.setFrom(new InternetAddress(account,"XXX"));        //可以设置发件人的别名
                //mimeMessage.setFrom(new InternetAddress(account));    //如果不需要就省略
                //收件人
                mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
                //主题
                mimeMessage.setSubject(subject);
                //时间
                mimeMessage.setSentDate(new Date());
                //容器类,可以包含多个MimeBodyPart对象
                Multipart mp = new MimeMultipart();
                
                //MimeBodyPart可以包装文本,图片,附件
                MimeBodyPart body = new MimeBodyPart();
                //HTML正文
                body.setContent(content, "text/html; charset=UTF-8");
                mp.addBodyPart(body);
                
                //添加图片&附件
                body = new MimeBodyPart();
                body.attachFile(fileStr);
                mp.addBodyPart(body);
                
                //设置邮件内容
                mimeMessage.setContent(mp);
                //仅仅发送文本
                //mimeMessage.setText(content);
                mimeMessage.saveChanges();
                Transport.send(mimeMessage);
            } catch (MessagingException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        
    
    }

    考虑到实际中要保证吞吐量,我写了一个线程:

    package mail.demo;
    
    public class Sending implements Runnable{
    
        private String to;    //收件人
        private String subject;    //主题
        private String content;    //内容
        private String fileStr;    //附件路径
    
        public Sending(String to, String subject, String content, String fileStr) {
            this.to = to;
            this.subject = subject;
            this.content = content;
            this.fileStr = fileStr;
        }
    
        @Override
        public void run() {
            SendEmailUtil sendEmail = new SendEmailUtil(to, subject, content, fileStr);
            sendEmail.send();
        }
    
    }

    线程的建立销毁开销也是很大的,我建了一个线程池,如果遇到批量处理的话可以好用一些。

    package mail.demo;
    
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    
    /**
     * 单例,线程池
     * @author Taozi
     *
     */
    public class SendingPool {
        
        private SendingPool() {
        }
        private static class Inner{
            private static SendingPool instance = new SendingPool();
        }
        
        public static SendingPool getInstance(){
            return Inner.instance;
        }
        
        private static int nThreads = 10;
        private static ExecutorService executor = Executors.newFixedThreadPool(nThreads);
        
        public SendingPool addThread(Sending sending){
            executor.execute(sending);
            return getInstance();
        }
        
        public void shutDown(){
            executor.shutdown();
        }
    }

     下面是测试类

    package mail.demo;
    
    public class MyTest {
    
        public static void main(String[] args) {
            SendingPool pool = SendingPool.getInstance();
            
            pool.addThread(new Sending("收件人", "AAA", createEmail().toString(), "file/1.jpg")).shutDown();
            
        }
        
        private static StringBuilder createEmail() {
            StringBuilder emailContent = new StringBuilder("<!DOCTYPE html><html><head><meta charset='UTF-8'><title>快来买桃子</title><style type='text/css'>        .container{            font-family: 'Microsoft YaHei';             600px;            margin: 0 auto;            padding: 8px;            border: 3px dashed #db303f;            border-radius: 6px;        }        .title{            text-align: center;            color: #db303f;        }        .content{            text-align: justify;            color: #717273;            font-weight: 600;        }        footer{            text-align: right;            color: #db303f;            font-weight: 600;            font-size: 18px;        }</style></head><body><div class='container'><h2 class='title'>好吃的桃子</h2><p class='content'>桃子含有维生素A、维生素B和维生素C,儿童多吃桃子可使身体健康成长,因为桃子含有的多种维生索可以直接强化他们的身体和智力。</p><footer>联系桃子:11110000</footer></div></body></html>");
            return emailContent;
        }
    }

     提示:实际中不要调用shutDown方法,因为这个是优雅关闭线程池的,如果你关闭了再次调用是会出问题的哟

     提示2:如果你不需要附件的功能,请把附件相关的代码注释,或者加个判断

    //添加图片&附件
    if(fileStr != null){
        body = new MimeBodyPart();
        body.attachFile(fileStr);
        mp.addBodyPart(body);
    }

     下面是我收到的邮件,Html正文+附件

     到此就完成了

     完整代码去GitHub下载,Javamail

     2019-07-29更新https://www.cnblogs.com/LUA123/p/11265995.html

    小伙伴们在使用过程中遇到各种各样的问题,在下一一列举。

    =============================================================================================

    错误1:

     javax.mail.AuthenticationFailedException: 535 Error: authentication failed, system busy
     
    身份验证失败,大多数都是这个问题。一种说法是账户密码不是登录密码,而是“授权码”;另外一种是“客户端专用密码

    关于客户端专用密码 。

    如果说您绑定了微信,就不能继续使用登录密码了,取代的是“客户端专用密码

     这里借用一下热心网友的截图,以下是绑定微信后的安全设置:登录方式和专用密码。

    如果你开启了这些东西,那么在使用Javamail的时候,密码就要用生成的“专用密码

    关于“授权码

    我想说:“不存在的”,如果你用的是企业邮,那么就不需要这个东西吧,你用个人的才需要(纯属猜测,本人也没用过)

     关于发信量

    有的小伙伴跟我说发了一定数量就不行了,我特地去查了查,原来这里是个坑对于频繁发送的场景十分不利),截图如下:

    所以,我建议想要无限频繁发送,那就去别的提供商看看,或者自己搭建邮件服务器

  • 相关阅读:
    题目1202:排序------注意每个数字的后面都有空格
    题目1178:复数集合------------结构体的的比较,cmp()函数的错误让我WA了多次
    题目1041:Simple Sorting-------注意最后一个数字的处理
    题目1034:寻找大富翁---用了sort()函数,注意头文件;
    题目1415:不一样的循环队列------注意细节小地方循环队列注意%M;还有为什么M要加一!!!!!!!!!!!!!
    题目1342:寻找最长合法括号序列II---注意:不要求就近匹配,只要求( 在 )前面的任一个位置即可
    题目1398:移动次数-----最少移动的次数,那么相同的最大值越靠后越好,相同的最小值越靠前越好
    题目1375:陈博的完美主义(25分)----------------题目中对输入数字的长度有要求,所以输入字符串,用atoi()转换函数
    题目1363:欢乐斗地主------用数组计数的应用,注意1和2得排在最后,表示最大
    题目1174:查找第K小数-------qsort()可以直接对数组用;还有用unique(a,a+n);的,服!
  • 原文地址:https://www.cnblogs.com/LUA123/p/5575134.html
Copyright © 2011-2022 走看看