使用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
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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;
}

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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);
}

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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("邮件发送失败!!!");
        }
    }
}

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
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;
    }
 
 
 
}

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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);
    }
}

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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];
    }
}

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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 @   不忘初心2021  阅读(442)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示