Email郵件發送與激活


1.導包

<!--發送郵件 https://mvnrepository.com/artifact/com.sun.mail/javax.mail -->
        <dependency>
            <groupId>com.sun.mail</groupId>
            <artifactId>javax.mail</artifactId>
            <version>1.6.2</version>
        </dependency>

2.配置文件

mail.propertiex

#服務器主機名 smtp.xx.com
mail.host=smtp.qq.com
mail.username=XXXXXX@qq.com
#密碼/客戶端授權碼
mail.password=XXXXXXXXXX
#編碼字符
mail.defaultEncoding=utf-8
#是否進行用戶名密碼校驗
mail.auth=true
#設置超時時間
mail.timeout=20000

3.配置到容器中

<!--
           讀取郵件配置文件,
           其中ignore-unresolvable="true"屬性是配置文件中存在
           多個property-placeholder時出現解析不了的占位符進行忽略掉,
       -->
    <context:property-placeholder location="classpath:mail.properties" ignore-unresolvable="true"/>
 <!--配置郵件接口-->
    <bean id="javaMailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
        <property name="host" value="${mail.host}"/>
        <property name="username" value="${mail.username}"/>
        <property name="password" value="${mail.password}"/>
        <property name="defaultEncoding" value="${mail.defaultEncoding}"/>
        <property name="javaMailProperties">
            <props>
                <prop key="mail.smtp.auth">${mail.auth}</prop>
                <prop key="mail.smtp.timeout">${mail.timeout}</prop>
            </props>
        </property>
    </bean>

4.工具類

import freemarker.cache.FileTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.Data;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.InputStream;
import java.util.Map;

@Data
@SuppressWarnings("all")
public class SendEmail {
    //發送標題
    private String title = null;
    //郵件內容,可以是html標簽 "<h2 style='color=red'>你好</h2>"
    private String emailContext = null;
    //默認開啟HTML標簽
    private Boolean flag = true;
    //附件名
    private String fileName = null;
    //附件路徑 new File("E:\\Pixiv PE\\36933.png")
    private File filePath = null;
    //發送郵件的人
    private String sendName = "dlb@qq.com";

    //獲取spring中的bean  JavaMailSenderImpl
    public JavaMailSenderImpl getJavaMailSenderImpl() throws MessagingException {
        AbstractApplicationContext as = new ClassPathXmlApplicationContext("applicationContext.xml");
        return as.getBean("javaMailSender",JavaMailSenderImpl.class);
    }

    /**
     * 發送前先准備上面的參數
     * @param recipients 收件人
     * @throws MessagingException 發送失敗
     */
    public void sendEmailTo(String recipients) throws MessagingException {
        JavaMailSenderImpl javaMailSender = getJavaMailSenderImpl();
        //創建消息對象
        MimeMessage mimeMessage =javaMailSender.createMimeMessage();
        //返回組裝次對象
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "utf-8");
        helper.setSubject(title);//發送標題
        helper.setText(emailContext,flag);//富文本
        //抄送
       // helper.setCc("");
        //密送
        //helper.setBcc("");
        //回復郵件
        //simpleMailMessage.setReplyTo();
        //設置發送日期
        //simpleMailMessage.setSentDate();
        //普通附件.bin文件
        //helper.addInline("myLogo", new File("E:\\Pixiv PE\\36933.png"));
        //附件
        if (fileName != null && filePath != null)
            helper.addAttachment(fileName,filePath);
        //發送
        helper.setTo(recipients);//接收人
        helper.setFrom("大蘿北"+'<'+sendName+'>');//發送人
        javaMailSender.send(mimeMessage);
    }

    /**
     * 以上傳的形式發送郵件
     * @param multipartFile  要上傳的文件
     * @param recipients    接收人
     * @throws Exception    上傳的文件或發送失敗
     */
    public void uploadEmailTo(MultipartFile multipartFile, String recipients) throws Exception {
        InputStream inputStream = multipartFile.getInputStream();
        byte[] buffer = new byte[inputStream.available()];
        inputStream.read(buffer);//讀到內存
        JavaMailSenderImpl javaMailSender = getJavaMailSenderImpl();
        //創建消息對象
        MimeMessage mimeMessage =javaMailSender.createMimeMessage();
        //返回組裝次對象
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "utf-8");
        helper.setSubject(title);//發送標題
        helper.setText(emailContext,flag);//富文本
        helper.addAttachment(multipartFile.getOriginalFilename(),new ByteArrayResource(buffer));
        helper.setTo(recipients);//接收人
        helper.setFrom("坑人網"+'<'+sendName+'>');//發送人
        javaMailSender.send(mimeMessage);
    }


    /**
     * 激活郵件用
     * @param recipients 接收人
     * @throws MessagingException 郵件發送失敗
     */
    public void activateEmailTo(String recipients) throws MessagingException {
        JavaMailSenderImpl javaMailSender = getJavaMailSenderImpl();
        //創建消息對象
        MimeMessage mimeMessage =javaMailSender.createMimeMessage();
        //返回組裝次對象
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "utf-8");
        helper.setSubject(title);//發送標題
        helper.setText(emailContext,flag);//富文本
        helper.setTo(recipients);//接收人
        helper.setFrom("坑人網"+'<'+sendName+'>');//發送人
        javaMailSender.send(mimeMessage);
    }
    /**
     * 獲取模板字符串
     * @param templateName 模板名字
     * @param data 模板中要添加的數據
     * @return 模板的字符串 出異常(只會出獲取模板異常)有返回空的字符串
     */
    public String setTemplateString(String templateName, Map map){
        Configuration configurer = new Configuration();
        try {
            //Template template = configurer.getTemplate(templateName, "utf-8");
            //使用FileTemplateLoader
            TemplateLoader templateLoader = new FileTemplateLoader(new File("C:\\Code\\Car_ssm\\"));
            String path = "web\\WEB-INF\\temp\\"+templateName;
            configurer.setTemplateLoader(templateLoader);
            Template template = configurer.getTemplate(path, "UTF-8");
            //寫入
            String s = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
            return s;
        } catch (Exception e){
            e.printStackTrace();
        }
        return "";
    }
}

5.測試服務

  @Autowired
    private JavaMailSenderImpl javaMailSender;

    @Test
    public void aa(){
        SendEmail sendEmail = new SendEmail();
        sendEmail.setTitle("大蘿北學java");
        sendEmail.setEmailContext("滴答滴答~~咕咕咕");
        try {
            sendEmail.sendEmailTo("279080122@qq.com");
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
    //測試激活郵件
    @Test
    public void bb(){
        String s = VerifyCodeUtils.generateVerifyCode(4);
        System.err.println(s);
        SendEmail sendEmail = new SendEmail();
        sendEmail.setTitle("送你的好東西!你懂得");
        sendEmail.setEmailContext("<h3><a href=\"www.gonogo.cn?code="+s+"\">點擊我,夜晚帶你探索自己"+s+"</a></h3>");
        try {
            sendEmail.sendEmailTo("279080122@qq.com");
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    //頁面模板激活
    @Test
    public void cc() throws Exception {
        String s = VerifyCodeUtils.generateVerifyCode(4);
        System.err.println(s);
        //准備頁面模板的內容值
        Map<String, String> map = new HashMap<>();
        map.put("adminName", "xxxxxxx馬寶國");
        map.put("activeUrl", "http://www.gonogo.cn/"+s);
        //裝載郵件內容
        SendEmail sendEmail = new SendEmail();
        String htmlText = sendEmail.setTemplateString("active.ftl", map);
        sendEmail.setTitle("送你的好東西!你懂得");
        sendEmail.setEmailContext(htmlText);
        try {
            //發送
            sendEmail.sendEmailTo("279080122@qq.com");
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void c()  {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();// 創建消息對象
        simpleMailMessage.setSubject("你好");
        simpleMailMessage.setText("dada");
        simpleMailMessage.setTo("279080122@qq.com");//接收人
        simpleMailMessage.setFrom("1216180134@qq.com");//發送人
        javaMailSender.send(simpleMailMessage);
    }
    @Test
    public void a2() throws MessagingException {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        //組裝
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
        helper.setSubject("主題1");//發送標題
        helper.setText("<h2 style='color=red'>你好</h2>",true);//
        //附件
        helper.addAttachment("2.jpg",new File("E:\\Pixiv PE\\36933.png"));
        helper.setTo("279080122@qq.com");//接收人
        helper.setFrom("1216180134@qq.com");//發送人
        javaMailSender.send(mimeMessage);
    }
    //暫且不用
    @Test
    public void testMail(){
        ////測試不用注入bean方式
        try {
            //讀取配置文件
            InputStream is = Test.class.getClassLoader().getResourceAsStream("util/mail.properties");
            Properties properties = new Properties();
            properties.load(is);
            System.out.println(properties.getProperty("mail.smtp.host"));
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        ////////////////////////////////////////////////////////
        AbstractApplicationContext as = new ClassPathXmlApplicationContext("applicationContext.xml");
        JavaMailSenderImpl javaMailSender = as.getBean("javaMailSender",JavaMailSenderImpl.class);
        MimeMessage mailMessage = javaMailSender.createMimeMessage();//創建郵件對象
        MimeMessageHelper mimeMessageHelper;
        Properties prop = new Properties();
        String from;
        try {
            // 從配置文件讀取發件人郵箱地址
            prop.load(this.getClass().getResourceAsStream("util/mail.properties"));
            from = prop.getProperty("mail.smtp.username");
            mimeMessageHelper = new MimeMessageHelper(mailMessage,true);
            mimeMessageHelper.setFrom(from); //發件人地址
            mimeMessageHelper.setTo("546279462@qq.com"); //收件人郵箱
            mimeMessageHelper.setSubject("郵件主題"); //郵件主題
            mimeMessageHelper.setText("<p style='color: red'>郵件內容123345</p>" +
                    "<img src='cid:06'/>",true); //true表示以html方式發送
            File file = new File("C:\\Users\\54627\\Pictures\\06.jpg"); //導入其他資源
            FileSystemResource resource = new FileSystemResource(file);
            mimeMessageHelper.addInline("06",resource); //可以指定id,在內容中引用(cid:id)
            mimeMessageHelper.addAttachment("06.jsp",resource); //附件
            javaMailSender.send(mailMessage);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        System.out.println("發送成功");
    }

    @Test
    public void sendMsg(){
        TencentMsg tencentMsg = new TencentMsg();
        String userInfo = "amanda";
        String msgCode = tencentMsg.getMsgCode();
        System.err.println("msgCode = " + msgCode);
        String msg = tencentMsg.sendLogin(msgCode,"1762136xxxx",userInfo);
        System.err.println("msg = " + msg);
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM