java 邮件发送

时间:2022-04-23
本文章向大家介绍java 邮件发送,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

步骤1:pom.xml添加依赖项

 1         <!--mail-->
 2 
 3         <dependency>
 4             <groupId>javax.mail</groupId>
 5             <artifactId>mailapi</artifactId>
 6             <version>1.4.2</version>
 7         </dependency>
 8 
 9         <dependency>
10             <groupId>javax.mail</groupId>
11             <artifactId>mail</artifactId>
12             <version>1.4.2</version>
13         </dependency>

步骤2:封装一个工具类(参考下面的代码)

注:BaseBean里其实没啥东西,就一个protected Logger logger,方便子类可以直接使用,大家参考时,可根据需要去掉BeseBean继承

  1 package com.cnblogs.yjmyzz.utils;
  2 
  3 import com.cnblogs.yjmyzz.domain.BaseBean;
  4 import org.springframework.util.StringUtils;
  5 
  6 import java.util.Properties;
  7 
  8 import javax.mail.Message;
  9 import javax.mail.MessagingException;
 10 import javax.mail.Session;
 11 import javax.mail.Transport;
 12 import javax.mail.internet.InternetAddress;
 13 import javax.mail.internet.MimeMessage;
 14 import javax.mail.internet.MimeUtility;
 15 
 16 /**
 17  * 邮件发送工具类
 18  */
 19 public class MailUtil extends BaseBean {
 20 
 21     private MimeMessage message;
 22     private Session session;
 23     private Transport transport;
 24     private String smtpHost = "";
 25     private int smtpPort = 25;
 26     private String senderUserName = "";
 27     private String senderPassword = "";
 28 
 29     public MailUtil(Properties properties, boolean debug) {
 30         this.smtpHost = properties.getProperty("mail.smtp.host");
 31         this.smtpPort = Integer.parseInt(properties.getProperty("mail.smtp.port"));
 32         this.senderUserName = properties.getProperty("mail.sender.username");
 33         this.senderPassword = properties.getProperty("mail.sender.password");
 34         session = Session.getInstance(properties);
 35         session.setDebug(debug);//开启后有调试信息
 36         message = new MimeMessage(session);
 37     }
 38 
 39     /**
 40      * 发送邮件
 41      *
 42      * @param subject        邮件主题
 43      * @param mailBody       邮件内容
 44      * @param senderNickName 发件人NickName
 45      * @param receiveUser    收件人地址
 46      * @param ccReceiveUser  抄送地址
 47      * @param bccReceiveUser 密送地址
 48      */
 49     public void sendEmail(String subject, String mailBody, String senderNickName,
 50                           String receiveUser, String ccReceiveUser, String bccReceiveUser, Boolean isHtmlFormat) {
 51         try {
 52             // 发件人
 53             InternetAddress from = null;
 54             if (StringUtils.isEmpty(senderNickName)) {
 55                 from = new InternetAddress(senderUserName);
 56             } else {
 57                 from = new InternetAddress(MimeUtility.encodeWord(senderNickName) + " <" + senderUserName + ">");
 58             }
 59             message.setFrom(from);
 60 
 61             // 收件人
 62             InternetAddress to = new InternetAddress(receiveUser);
 63             message.setRecipient(Message.RecipientType.TO, to);
 64 
 65             //抄送人
 66             if (!StringUtils.isEmpty(ccReceiveUser)) {
 67                 InternetAddress cc = new InternetAddress(ccReceiveUser);
 68                 message.setRecipient(Message.RecipientType.CC, cc);
 69             }
 70 
 71             //密送人
 72             if (!StringUtils.isEmpty(bccReceiveUser)) {
 73                 InternetAddress bcc = new InternetAddress(bccReceiveUser);
 74                 message.setRecipient(Message.RecipientType.BCC, bcc);
 75             }
 76 
 77             message.setSubject(subject);
 78             String content = mailBody.toString();
 79 
 80             if (isHtmlFormat) {
 81                 message.setContent(content, "text/html;charset=UTF-8");
 82             } else {
 83                 message.setContent(content, "text/plain;charset=UTF-8");
 84             }
 85             message.saveChanges();
 86             transport = session.getTransport("smtp");
 87             transport.connect(smtpHost, smtpPort, senderUserName, senderPassword);
 88             transport.sendMessage(message, message.getAllRecipients());
 89 
 90             logger.debug(senderUserName + " 向 " + receiveUser + " 发送邮件成功!");
 91 
 92         } catch (Exception e) {
 93             e.printStackTrace();
 94             logger.error("sendEmail失败!", e);
 95         } finally {
 96             if (transport != null) {
 97                 try {
 98                     transport.close();
 99                 } catch (MessagingException e) {
100                     e.printStackTrace();
101                     logger.error("sendEmail->transport关闭失败!", e);
102                 }
103             }
104         }
105     }
106 
107 }

步骤3:配置

a) 属性文件mail.properties

1 mail.smtp.host=smtp.qq.com
2 mail.smtp.port=25
3 mail.smtp.auth=true
4 mail.sender.username=xxx@qq.com
5 mail.sender.password=***

b) spring配置注入

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
 4        xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
 5        xmlns:context="http://www.springframework.org/schema/context"
 6        xsi:schemaLocation="
 7      http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
 8      http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
 9      http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
10      http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
11      http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"
12        default-autowire="byName">
13 
14     <bean id="mailProperties"
15           class="org.springframework.beans.factory.config.PropertiesFactoryBean">
16         <property name="location"
17                   value="classpath:mail.properties"/>
18     </bean>
19 
20     <bean id="mailUtil" class="com.cnblogs.yjmyzz.utils.MailUtil">
21         <constructor-arg index="0" ref="mailProperties"/>
22         <constructor-arg index="1" value="false"/>
23     </bean>
24 
25 </beans>

测试代码:

1     @Test
2     public void testSendMail() {
3         ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-context.xml");
4         MailUtil mailUtil = ctx.getBean(MailUtil.class);
5         mailUtil.sendEmail("骚年,崛起吧,人类需要你!", "<font color=red>骚年:</font><h1>快去拯救地球吧!</h1>", "菩提树上的杨过", "aaa@126.com", "bbb@infosky.com.cn", "ccc@sjtu.edu.cn", true);
6         ((ClassPathXmlApplicationContext) ctx).close();
7     }