使用javax.mail实现邮件的简单发送

<?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>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.0</version>
        <relativePath/>
    </parent>

    <groupId>com.mail</groupId>
    <artifactId>mail-service</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <!--tomcat容器-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--lombok依赖-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.16</version>
        </dependency>
        <!--邮件发送相关依赖三个-->
        <dependency>
            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils</artifactId>
            <version>1.9.4</version>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4.7</version>
        </dependency>
        <!--引入junit单元测试依赖-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
        <finalName>qiuxie</finalName>
    </build>


</project>
View Code
package com.mail;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @Description:
 * @Author: Yourheart
 * @Create: 2023/1/29 10:45
 */
@SpringBootApplication
public class MailApplication {
    public static void main(String[] args) {
        SpringApplication.run(MailApplication.class,args);

    }
}

  

server.port=8081

china.com:smtp.china.com
soim.net:freemail.soim.com
bjmail.net:bjmail.net
263.net.cn:263.net.cn
gz168.net:email.gz168.net
mailbox.com.cn:email.com.cn
yes100.com:smtp.yes100.com
mail.bodachina.com:mail.bodachina.com
foxmail.com.cn:smtp.foxmail.com.cn
email.com.cn:www.email.com.cn
tom.com:smtp.tom.com
peoplemail.com.cn:smtp.peoplemail.com.cn
kali.com.cn:smtp.kali.com.cn
x263.net:smtp.x263.net
ccidnet.com:smtp.ccident.com
7119.net:smtp.7119.net
public.guangzhou.gd.cn:public.guangzhou.gd.cn
yahoo.com.ar:smtp.mail.yahoo.com.ar
yahoo.com.au:smtp.mail.yahoo.com.au
yifan.net:yifan.net
yahoo.es:smtp.mail.yahoo.es
yahoo.co.kr:smtp.mail.yahoo.co.kr
yahoo.no:smtp.mail.yahoo.no
tt.zj.cn:smtp.email.com.cn
netease.com:smtp.netease.com
yahoo.com.tw:smtp.mail.yahoo.com.tw
softhome.net:smtp.SoftHome.net
363.net:smtp.363.net
cfe21.com:www.cfe21.com
sina.com:smtp.sina.com.cn
hnet.com.cn:smtp.email.com.cn
yahoo.com.br:smtp.mail.yahoo.com.br
fengyun.net:freemail.fengyun.net
newstar.com.cn:smtp.email.com.cn
yahoo.co.jp:smtp.mail.yahoo.co.jp
chinaxian.com:www.email.com.cn
china183.com:mail.china183.com
yahoo.fr:smtp.mail.yahoo.fr
yahoo.com:smtp.mail.yahoo.com
bodachina.com:smtp.bodachina.com
freemail.online.tj.cn:freemail.online.tj.cn
gzpublic.guangzhou.gd.cn:gzpublic.guangzhou.gd.cn
dfworld.net:mail.dfworld.net
dl163.com:www.dl163.com
yahoo.com.cn:smtp.mail.yahoo.com.cn
21cn.com:smtp.21cn.com
fd21.com:smtp.fd21.com
sohu.com:smtp.sohu.com
elawchina.com:smtp.elawchina.com
citiz.net:smtp.citiz.net
fugao.net:smtp.email.com.cn
gzyp21.net:gzyp21.net
freemail.nx.cninfo.net:freemail.nx.cninfo.net
btamail.net.cn:btamail.net.cn
263.net:smtp.263.net
gzboy.com:www.email.com.cn
yahoo.com.mx:smtp.mail.yahoo.com.mx
yahoo.ca:smtp.mail.yahoo.ca
etang.com:smtp.etang.com
371.net:smtp.371.net
wx88.net:mail.wx88.net
km169.net:email.km169.net
990.net:990.net
163.com:smtp.163.com
139.com:smtp.139.com
yeah.net:smtp.yeah.net
myrice.com:smtp.myrice.com
sh163.net:mail.sh163.net
yahoo.se:smtp.mail.yahoo.se
2888.com:2888.com
mybada.net:smtp.mybada.net
yahoo.de:smtp.mail.yahoo.de
elong.com:smtp.elong.com
yahoo.dk:smtp.mail.yahoo.dk
chinese.com:smtp.chinese.com
20520.com:smtp.20520.com
777.net.cn:mail.777.net.cn
cmmail.com:smtp.cmmail.com
cnuninet.com:smtp.bj.cnuninet.com
focus.com.cn:smtp.focus.com.cn
eazier.com:smtp.eazier.com
yesky.com:smtp.yesky.com
mweb.com.cn:smtp.mweb.com.cn
cww.com:smtp.china.com
100m.hl.cninfo.net:100m.hl.cninfo.net
online.sh.cn:smtp.citiz.net
21cn.net:smtp.21cn.net
yahoo.it:smtp.mail.yahoo.it
cityhot.com:citymail.cityhot.com
163.net:smtp.163.net
dg.163mail.net:dg.163mail.net
soyou.net:smtp.soyou.net
w4f.com:smtp.email.com.cn
alibaba.com:smtp.alibaba.com
wocall.com:wocall.com
kzinfo.net:mail.kzinfo.net
yahoo.com.hk:smtp.mail.yahoo.com.hk
nethao.com:freemail.nethao.com
tonghua.com.cn:smtp.tonghua.com.cn&nbsp;&nbsp;
fm365.com:mail.fm365.com
88998.com:202.100.222.86
yahoo.co.uk:smtp.mail.yahoo.co.uk
telekbird.com.cn:smtp.telekbird.com.cn
2911.net:smtp.2911.net
8848.net:smtp.8848.net
guohao.com:guohao.com
View Code
package com.mail.entity;

import lombok.Data;

import java.util.Date;

/**
 * @Description:
 * @Author: Yourheart
 * @Create: 2023/1/29 10:54
 */
@Data
public class MimeMessageDTO {
    /**
     * 变量名 subject: TODO 邮件标题
     */
    private String subject;

    /**
     * 变量名 sentDate: TODO 邮件日期
     */
    private Date sentDate;

    /**
     * 变量名 text: TODO 邮件内容
     */
    private String text;

    /**
     * 目标邮箱
     */
    private String targetAddress;
}

  

package com.mail.service;

import com.mail.entity.MimeMessageDTO;

/**
 * @Description:
 * @Author: Yourheart
 * @Create: 2023/1/29 10:49
 */
public interface SendMailsService {

     /**
      * 邮件测试
      * @param mimeMessageDTO
      */
     void sendMail(MimeMessageDTO mimeMessageDTO);
}

  

package com.mail.service.impl;

import com.mail.entity.MimeMessageDTO;
import com.mail.service.SendMailsService;
import com.mail.util.MailUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @Description:
 * @Author: Yourheart
 * @Create: 2023/1/29 10:52
 */
@Service
@Slf4j
public class SendMailsServiceImpl implements SendMailsService {

    /**
     * 邮件测试
     *
     * @param mimeMessageDTO
     */
    @Override
    public void sendMail(MimeMessageDTO mimeMessageDTO) {
        //用户邮箱地址
        String userName = "123@163.com";
        //授权码
        String password = "123";
        // 发送单邮件
        if (MailUtil.sendGroupEmail(userName, password, mimeMessageDTO.getTargetAddress(), mimeMessageDTO)) {
            log.info("邮件发送成功!");
        } else {
            log.info("邮件发送失败!!!");
        }
    }
}

 

package com.mail.util;

import com.mail.entity.MimeMessageDTO;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.List;
import java.util.Properties;

/**
 * @Description:
 * @Author: Yourheart
 * @Create: 2023/1/29 10:56
 */
@Slf4j
@Data
public class MailUtil {

    /**
     * 变量名 userName: TODO 邮箱用户名
     */
    private String userName;

    /**
     * 变量名 password: TODO 邮箱地址
     */
    private String password;

    /**
     * 变量名 smtpHost: TODO 邮箱smtp地址,发送地址
     */
    private String smtpHost;

    /**
     * 变量名 targetAddress: TODO 目标邮箱地址
     */
    private String targetAddress;

    /**
     *  发送单邮件
     * @param userName
     * @param password
     * @param targetAddress
     * @param mimeDTO
     * @return
     */
    public  static boolean sendEmail(String userName,String password,String targetAddress,
                                     MimeMessageDTO mimeDTO){
        return publicsendEmail(userName,password,targetAddress,mimeDTO,false,null);
    }
    /**
     * 发送单邮件(附件)
     * @param userName
     * @param password
     * @param targetAddress
     * @param mimeDTO
     * @param filepath        文件本地绝对路径
     * @return
     */
    public  static boolean sendEmailByFile(String userName,String password,String targetAddress,
                                           MimeMessageDTO mimeDTO,List<String> filepath){
        return publicsendEmail(userName,password,targetAddress,mimeDTO,true,filepath);
    }
    /**
     * 群发邮件
     * @param userName
     * @param password
     * @param targetAddress   多个邮件发送地址,以,分隔
     * @param mimeDTO
     * @return
     */
    public  static boolean sendGroupEmail(String userName,String password,String targetAddress,
                                          MimeMessageDTO mimeDTO){
        return publicsendEmail(userName,password,targetAddress,mimeDTO,true,null);
    }
    /**
     * 群发邮件 (附件)
     * @param userName
     * @param password
     * @param targetAddress 多个邮件发送地址,以,分隔
     * @param mimeDTO
     * @param filepath      文件本地绝对路径
     * @return
     */
    public  static boolean sendGroupEmailByFile(String userName,String password,String targetAddress,
                                                MimeMessageDTO mimeDTO,List<String> filepath){
        return publicsendEmail(userName,password,targetAddress,mimeDTO,true,filepath);
    }



    /**
     * 邮件发送基础方法
     * @param userName
     * @param password
     * @param targetAddress
     * @param mimeDTO
     * @param isGroup
     * @param filepath
     * @return
     */
    private static boolean publicsendEmail(String userName,String password,String targetAddress,
                                           MimeMessageDTO mimeDTO,boolean isGroup,List<String> filepath){
        Properties props = makeMailProperties(userName);
        String hostname= SMTPUtil.simpleMailSender(userName);
        Session session = Session.getInstance(props, new PopupAuthenticator(userName, password));
        session.setDebug(false);
        try {
            Transport ts = session.getTransport();
            ts.connect(hostname,userName,password);
            Message message =!isGroup?createEmail(session,userName,targetAddress,mimeDTO)
                    :createEmailByGroupAndFile(session,userName,
                    targetAddress,mimeDTO,filepath==null?null:filepath);
            ts.sendMessage(message,message.getAllRecipients());
            ts.close();
        } catch (Exception mex) {
            mex.printStackTrace();
            return false;
        }
        return true;
    }





    /**
     * 创建邮件信息
     * @param userName
     * @return
     */
    private static Properties makeMailProperties(String userName){
        Properties props = new Properties();
        String hostname=SMTPUtil.simpleMailSender(userName);
        log.info("hostname:{}",hostname);
        props.put("mail.smtp.host", hostname);
        props.setProperty("mail.smtp.auth", "true");
        props.setProperty("mail.transport.protocol", "smtp");
        if(hostname.indexOf(".qq.com")!=-1){
            props.setProperty("mail.smtp.socketFactory.port", "465");
            props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        }
        return props;
    }



    /**
     * 创建邮件
     * @Author Casper
     * Create_time:2015年10月17日 下午7:45:57
     * description:
     */
    private static Message createEmail(Session session,String userName,String regMail,MimeMessageDTO mimeDTO){
        MimeMessage message = new MimeMessage(session);
        try {
            message.setFrom(new InternetAddress(userName));
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(regMail));
            message.setSubject(mimeDTO.getSubject());
            message.setContent(mimeDTO.getText(),"text/html;charset=UTF-8");
            message.saveChanges();
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        return message;
    }
    /**
     * 创建群发带附件
     * @return
     */
    private static Message createEmailByGroupAndFile(Session session,String userName,
                                                     String regMail,MimeMessageDTO mimeDTO,List<String> filepath){
        MimeMessage message = new MimeMessage(session);
        try {
            message.setFrom(new InternetAddress(userName));
            // 创建收件人列表
            if (regMail != null && regMail.trim().length() > 0) {
                String[] arr = regMail.split(",");
                int receiverCount = arr.length;
                if (receiverCount > 0) {
                    InternetAddress[] address = new InternetAddress[receiverCount];
                    for (int i = 0; i < receiverCount; i++) {
                        address[i] = new InternetAddress(arr[i]);
                    }
                    message.setRecipients(Message.RecipientType.TO, address);
                }
            }
            // 后面的BodyPart将加入到此处创建的Multipart中
            Multipart mp = new MimeMultipart();
            // 附件操作
            if (filepath != null && filepath.size() > 0) {
                for (String filename : filepath) {
                    MimeBodyPart mbp = new MimeBodyPart();
                    // 得到数据源
                    FileDataSource fds = new FileDataSource(filename);
                    // 得到附件本身并至入BodyPart
                    mbp.setDataHandler(new DataHandler(fds));
                    // 得到文件名同样至入BodyPart
                    mbp.setFileName(fds.getName());
                    mp.addBodyPart(mbp);
                }
                MimeBodyPart mbp = new MimeBodyPart();
                mbp.setText(mimeDTO.getText());
                mp.addBodyPart(mbp);
                // 移走集合中的所有元素
                filepath.clear();
                // Multipart加入到信件
                message.setContent(mp);
            } else {
                // 设置邮件正文
//            	message.setText(mimeDTO.getText());
                message.setContent(mimeDTO.getText(),"text/html;charset=UTF-8");
            }
            message.setSubject(mimeDTO.getSubject());
            message.saveChanges();
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        return message;
    }



}

  

package com.mail.util;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;

/**
 * @Description:
 * @Author: Yourheart
 * @Create: 2023/1/29 10:59
 */
public class PopupAuthenticator extends Authenticator {
    private String username = null;
    private String password = null;

    public PopupAuthenticator(String user, String pass) {
        this.username = user;
        this.password = pass;
    }
    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(username, password);
    }
}

  

package com.mail.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * @Description:
 * @Author: Yourheart
 * @Create: 2023/1/29 10:59
 */
public class SMTPUtil {
    /**
     * 方法名: SimpleMailSender 功能描述: TODO 简单的smtp生成,大部分是有用的,建议自己建立smtp库....
     *
     * @param: @param userName
     * @param: @return
     * @return: String
     */
    public static String simpleMailSender(String userName) {
        return "smtp." + getHost(userName);
    }

    /**
     * @Title: getSMTPAddress @Description: TODO (这里用一句话描述这个方法的作用) @param @param
     * userName @param @return 设定文件 @return String 返回类型 @throws
     */
    public static String getSMTPAddress(String userName) {
        String smtpAddress = null;
        Properties props = new Properties();
        try {
            //InputStream in = SMTPUtil.class.getResourceAsStream("/mail.properties");
            InputStream in = SMTPUtil.class.getResourceAsStream("application.properties");
            props.load(in);
            // 读取properties的内容
            smtpAddress = props.getProperty(getHost(userName).trim());
            // 没有获取到
            if (smtpAddress == null) {
                // 生成简单得
                smtpAddress = simpleMailSender(userName);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return smtpAddress;
    }

    /**
     * @Title: getHost @Description: TODO 得到 邮箱@后面得字符 @param @param
     * userName @param @return 设定文件 @return String 返回类型 @throws
     */
    public static String getHost(String userName) {
        return userName.split("@")[1];
    }
}

  

package com.mail;

import com.mail.entity.MimeMessageDTO;
import com.mail.service.SendMailsService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.Date;

import static org.junit.Assert.*;

@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
public class MailApplicationTest {

    @Autowired
    private SendMailsService sendMailsService;

    @Test
    public void main() {

        StringBuilder stringBuilders = new StringBuilder();
        stringBuilders.append("345@163.com");
        MimeMessageDTO mimeDTO = new MimeMessageDTO();
        mimeDTO.setSentDate(new Date());
        mimeDTO.setTargetAddress(stringBuilders.toString());
        mimeDTO.setSubject("测试邮件");
        mimeDTO.setText("干嘛呢");
        sendMailsService.sendMail(mimeDTO);
    }
}

 

以上就是javax.mail实现邮件发送的全部代码部分

 

posted @ 2023-01-29 21:11  不忘初心2021  阅读(418)  评论(0编辑  收藏  举报