springBoot项目中如何整合javamail 群发邮件操作

第一步,在resources下建立一个mail.properties文件

mail.smtp.service=smtp.qq.com
#465/587
mail.smtp.port=587

mail.from.address=你服务邮箱

mail.from.smtp.pwd=自己开启qq邮箱设置的独立密码(在邮箱-设置 下面)

mail.from.nickname=随便自己怎么搞

第二步

准备几个工具类

第一个

package com.xuemeng.mail;


import java.util.Locale;
import java.util.ResourceBundle;


/**
 * @author xuemeng
 * @date 2018/12/13 11:29
 */
public class PropertiesUtil  {

        private final ResourceBundle resource;
        private final String fileName;

        public PropertiesUtil (String fileName) {
                this.fileName = fileName;
                Locale locale=new Locale("zh","CN");
                this.resource=ResourceBundle.getBundle(this.fileName,locale);
        }
        public String getValue(String key){
                String message=this.resource.getString(key);
                return message;
        }
}

第二个

package com.xuemeng.mail;


/**
 * @author xuemeng
 * @date 2018/12/13 11:38
 */
public enum MailContentTypeEnum {

        HTML("text/html;charset=UTF-8"),//html格式
        TEXT("text");
        private String value;

        MailContentTypeEnum(String value){
                this.value=value;
        }
        public String getValue(){
                return value;
        }

}

第三个

package com.xuemeng.mail;


import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;


/**
 * @author xuemeng
 * @date 2018/12/13 10:59
 */
public class MailEntity implements Serializable {
        //此处填写smtp服务器
        private String smtpService;
        //设置端口号
        private String smtpPort;
        //设置发送youxiang
        private String formMailAddress;
        //设置发送口令
        private String formMailStmpPwd;
        //设置标题
        private String title;
        // 内容
        private String content;
        //格式html
        private String contentType;
        //收件(接受)邮箱集合
        private List list=new ArrayList<>();

//省略getset方法

}

第四个

package com.xuemeng.mail;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import java.util.List;
import java.util.Properties;


/**
 * @author xuemeng
 * @date 2018/12/13 11:14
 * pwd:qgyantrvozembeji
 *  //第三方登陆qq密码:qgyantrvozembeji
 */
public class MailSender {
        //实例化一个mail对象
      private static  MailEntity mail=new MailEntity();

        /**
         * 设置标题
         * @param title
         * @return
         */
        public MailSender title(String title){
                mail.setTitle(title);
                return this;
        }

        /**
         * 设置邮件内容
         * @param content
         * @return
         */
        public MailSender content(String content){
                mail.setContent(content);
                return this;
        }

        /**
         * 邮件内容格式
         * @param typeEnum
         * @return
         */
        public MailSender contentType(MailContentTypeEnum typeEnum){
                mail.setContentType(typeEnum.getValue());
                return this;
        }

        /**
         * 目标邮箱
         * @param targets
         * @return
         */
        public MailSender target(List targets){
                mail.setList(targets);
                return this;
        }

        public void send() throws  Exception{

                if(mail.getContentType()==null){
                        mail.setContentType(MailContentTypeEnum.HTML.getValue());
                }
                if(mail.getContent()==null||mail.getContent().trim().length()==0){
                        throw new Exception("请填写邮件内容");
                }
                if(mail.getTitle()==null||mail.getTitle().trim().length()==0){
                        throw new Exception("请填写邮件标题");
                }
                if(mail.getList().size()==0){
                        throw new Exception("请填写要发送的人员");
                }

               final PropertiesUtil putil=new PropertiesUtil("mail");

                final Properties prop=new Properties();
                prop.put("mail.smtp.auth",true);
              /*  prop.put("mail.smtp.starttls.enable", "true");

                //不做服务器证书校验
                prop.put("mail.smtp.ssl.checkserveridentity", "false");

                //添加信任的服务器地址,多个地址之间用空格分开
                prop.put("mail.smtp.ssl.trust", putil.getValue("mail.smtp.service"));*/

                prop.put("mail.smtp.host",putil.getValue("mail.smtp.service"));
                prop.put("mail.smtp.port",putil.getValue("mail.smtp.port"));
                prop.put("mail.user",putil.getValue("mail.from.address"));
                prop.put("mail.password",putil.getValue("mail.from.smtp.pwd"));
                String username=prop.getProperty("mail.user");
                String password=prop.getProperty("mail.password");

           /*     Authenticator acthenticator=new Authenticator() {
                        @Override
                        protected PasswordAuthentication getPasswordAuthentication() {
                                String username=prop.getProperty("mail.user");
                                String pawwword=prop.getProperty("mail.password");
                                return new PasswordAuthentication(username,pawwword);
                        }
                };
*/
                Session mailsession=Session.getInstance(prop, new Authenticator() {
                        @Override
                        protected PasswordAuthentication getPasswordAuthentication() {
                                return new PasswordAuthentication(username,password);
                        }
                });

                MimeMessage message=new MimeMessage(mailsession);

                String nickname= MimeUtility.encodeText(putil.getValue("mail.from.nickname"));

                InternetAddress address=new InternetAddress(nickname+"<"+prop.getProperty("mail.user")+">");
                message.setFrom(address);
                message.setSubject(mail.getTitle());
                if(mail.getContentType().equals(MailContentTypeEnum.HTML.getValue())){
                        message.setContent(mail.getContent(),mail.getContentType());
                }
                else if(mail.getContentType().equals(MailContentTypeEnum.TEXT.getValue())){
                        message.setText(mail.getContent());
                }
                List targets=mail.getList();
                for(int i=0;i 
  

最后测试

package com.xuemeng;

import com.xuemeng.mail.MailContentTypeEnum;
import com.xuemeng.mail.MailSender;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.xml.soap.Text;
import java.util.ArrayList;
import java.util.List;


@RunWith(SpringRunner.class)
@SpringBootTest
public class ManagerApplicationTests {

               @Test
               public void contextLoads() {
                              /**
                               * 测试发送email
                               */
                              MailSender sender=new MailSender();
                              sender.title("测试邮件发送");
                              sender.content("简单文本发送");
                              sender.contentType(MailContentTypeEnum.TEXT);
                              List list=new ArrayList<>();
                              list.add("[email protected]");
                              list.add("[email protected]");
                              list.add("[email protected]");
                              sender.target(list);
                              try{
                              sender.send();
                              }catch (Exception e){
                                             e.printStackTrace();
                              }

               }

}

常见的问题

javax.mail.AuthenticationFailedException: 454 Authentication failed, please open smtp flag first!我用的是QQ邮箱,需要开启POP3/SMTP服务。

com.sun.mail.smtp.SMTPSendFailedException: 503 Error: need EHLO and AUTH first !需要验证,设置mail.smtp.auth为true。javax.mail.AuthenticationFailedException: 535 Authentication failed是QQ邮箱开头pop/smtp服务需要独立密码,就是你开启服务系统给的密码

com.sun.mail.smtp.SMTPSenderFailedException: 553 Envolope sender mismatch with login user验证的用户和发送者要一致
 

 

你可能感兴趣的:(java,学习,java,Web)