码迷,mamicode.com
首页 > 编程语言 > 详细

springboot_邮件

时间:2020-06-15 13:56:59      阅读:71      评论:0      收藏:0      [点我收藏+]

标签:char   ==   public   prope   tar   dem   pat   防止   service   

pom依赖:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.canzhen.demo</groupId>
    <artifactId>mailDemo</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>mailDemo</name>
    <description>邮件</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <!-- 发送邮件需要的jar java send mail  -->
        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4.5</version>
        </dependency>
        <dependency>
            <groupId>javax.activation</groupId>
            <artifactId>activation</artifactId>
            <version>1.1.1</version>
        </dependency>
    </dependencies>

</project>

工具:

package com.canzhen.mail.util;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
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 javax.mail.internet.MimeUtility;
import java.io.UnsupportedEncodingException;
import java.util.Properties;

public class MultiEmailUtil {
    private Properties props;//用来存储一些邮件的属性,设置几个等待时间什么的。
    private String[] params = new String[2];//用来存储发件人和授权码

    /**
     * @param transportType 邮件发送方式
     * @param serviceType 服务器类型
     * @param servicePort 服务器端口号
     * @param fromEMail   发件人
     * @param authPassword 授权码
     */
    public MultiEmailUtil(String transportType, String serviceType, String  servicePort, String fromEMail , String authPassword)
    {

        //       // 获取默认的 Session 对象。
        // 1.创建一个程序与邮件服务器会话对象 Session
        Properties tProps = new Properties();
        tProps.put("mail.transport.protocol", transportType);
        tProps.put("mail.smtp.host",serviceType );//smtp.exmail.qq.com 这个例子是qq的企业邮箱的服务器
        tProps.put("mail.smtp.port", servicePort);//一般默认都是 25
        // 指定验证为true
        tProps.setProperty("mail.smtp.auth", "true");
        // props.setProperty("mail.smtp.timeout","1000");
        tProps.put("mail.smtp.timeout", 100000);//这几个参数很有必要
        tProps.put("mail.smtp.connectiontimeout", 100000);//这几个参数很有必要
        tProps.put("mail.smtp.writetimeout",100000);//这几个参数很有必要
        props = (Properties) tProps.clone();
        params[0]=fromEMail;//如果可以最好弄一个加密的方式
        params[1]=authPassword;//如果可以最好弄一个加密的方式
    }

    /***
     *
     * @param mailTO    收件人集合,这个不可以为空,哈哈哈
     * @param mailCC    抄送人集合,可以传null,若果是null就当做没有抄送
     * @param contentTop 邮件标题,可以传null,默认值是 "您有,一封邮件待查收"
     * @param contentText 邮件正文,可以传null,默认值是 "各位好:"
     * @param fileName    附件的绝对地址,可以传null,如果是null就默认当做不添加附件
     */
    public boolean sendEmail(String[] mailTO,String[] mailCC,String contentTop,String contentText,String fileName)
    {
        //收件人不能是空
        if (mailTO == null || mailTO.length == 0)
            return false;
        // 认证
        Authenticator auth = new Authenticator() {
            @Override
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(params[0], params[1]);
            }
        };
        Session session = Session.getInstance(props, auth);//居然发现了一个final的类,和String一样,哈哈

        try{
            // 创建默认的 MimeMessage 对象。
            MimeMessage message = new MimeMessage(session);

            // Set From: 发件人,头部头字段
            message.setFrom(new InternetAddress(params[0]));

            Address addressesTO[] = new Address[mailTO.length];

            //循环收件人
            for (int i = 0; i < mailTO.length ; i++)
            {
                addressesTO[i] = (Address) new InternetAddress(mailTO[i]).clone();
            }
            message.addRecipients(Message.RecipientType.TO,addressesTO);//设置收件人
            //对抄送人进行处理
            if( ! (mailCC == null|| mailCC.length == 0)) {
                Address addressesCC[] = new Address[mailCC.length];
                //循环抄送人
                for (int i = 0; i < mailCC.length; i++)
                {
                    addressesCC[i] = (Address) new InternetAddress(mailCC[i]).clone();
                }
                message.addRecipients(Message.RecipientType.CC, addressesCC);//设置抄送人
            }
            // Set Subject: 头字段
            if(contentTop == null || contentTop.equals(""))
            {
                message.setSubject("您有,一封邮件待查收");
            }else {
                message.setSubject(contentTop);
            }
            // 创建消息部分
            BodyPart messageBodyPart = new MimeBodyPart();
            // 消息
            if(contentText == null || contentText.equals("")){
                messageBodyPart.setText("各位好:");
            }else{
                messageBodyPart.setText(contentText);
            }
            // 创建多重消息
            Multipart multipart = new MimeMultipart();
            // 设置文本消息部分
            multipart.addBodyPart(messageBodyPart);
            // String tFileName = fileName;
            //目前没有对目录做校验,后续再添加吧
            if (!( fileName == null || fileName.equals(""))){
                // 附件部分
                messageBodyPart = new MimeBodyPart();
                DataSource source = new FileDataSource(fileName);
                messageBodyPart.setDataHandler(new DataHandler(source));
                //就只这行可以防止乱码
                String newFileName =  MimeUtility.encodeText(source.getName(),"utf-8",null);
                messageBodyPart.setFileName(newFileName);
                multipart.addBodyPart(messageBodyPart);
            }

            // 发送完整消息
            message.setContent(multipart,"text/html;charset=utf-8");
            //   发送消息
            Transport.send(message);

            System.out.println("Sent message successfully....");

        }catch (MessagingException | UnsupportedEncodingException mex) {
            mex.printStackTrace();
        }
        return true;
    }
}

测试:

package com.canzhen.mail.test;

import com.canzhen.mail.util.MultiEmailUtil;

public class mailTest {
    public static void main(String[] args) {
        String[] mailTO = {"XXX@qq.com"};//收件人
        String[] mailCC = {"XXX@qq.com"};//抄送人
        String contentTop = "这是一个邮件的题目";
        String contentText = "这是这个邮件的正文";
        String fileName = "E:\\桌面壁纸\\哈哈.png";//如果有附件的话这填写地址
        new MultiEmailUtil("SMTP","smtp.qq.com","25","XXX@qq.com",
                "XXX").sendEmail(mailTO,mailCC,contentTop,contentText,fileName);
    }
}

 

springboot_邮件

标签:char   ==   public   prope   tar   dem   pat   防止   service   

原文地址:https://www.cnblogs.com/canzhen/p/13087808.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!