(一):电子邮件协议
电子邮件的在网络中传输和网页一样需要遵从特定的协议,常用的电子邮件协议包括 SMTP,POP3,IMAP。其中邮件的创建和发送只需要用到 SMTP协议,所有本文也只会涉及到SMTP协议。SMTP 是 Simple Mail Transfer Protocol 的简称,即简单邮件传输协议。
(二): JavaMail
下载地址:
https://java.net/projects/javamail/pages/Home
<!--发邮件POM-->
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version>
</dependency>
(三) 创建一封简单的电子邮件
邮件创建步骤:
创建一个邮件对象(MimeMessage);
设置发件人,收件人,可选增加多个收件人,抄送人,增加多个附件;
设置邮件的主题(标题);
设置邮件的正文(内容);
设置显示的发送时间;
保存到本地。
发送邮件首先需要有一个邮箱账号和密码,本文以网易163邮箱为例,邮箱账号必须要开启 SMTP 服务,在浏览器网页登录邮箱后一般在邮箱的“设置”选项中可以开启,并记下邮箱的 SMTP 服务器地址,如下所示(其他邮箱大同小异):
代码如下:
EmailController
package com.richfit.richfit.controller;
import com.richfit.richfit.service.EmailService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import javax.mail.Message;
import java.util.List;
/**
* @ClassName EmailController
* @Description:
* @Author BruthLi
* @Date 2020/2/7
* @Version V1.0
**/
@Api(value = "发邮件")
@Controller
@RequestMapping(value = "/sys/email")
public class EmailController {
@Autowired
private EmailService emailService;
@ApiOperation(value = "网易163邮箱发送到其他邮箱", notes = "网易163邮箱发送到其他邮箱")
@RequestMapping(value = "/sendemail", method = RequestMethod.POST)
public Message sendEmail(@ApiParam(name = "otherCount",value = "对方的邮箱号码可以是例如123@qq.com,234@qq.com",required = true) @RequestParam(value = "otherCount",required = true)String otherCount,
@ApiParam(name = "chaopSongCount",value = "抄送对方的邮箱号码可以是 例如'123@qq.com,234@qq.com'",required = false) @RequestParam(value = "chaopSongCount",required = false)String chaopSongCount,
@ApiParam(name = "subject",value = "标题",required = false)@RequestParam(value = "subject",required = false)String subject,
@ApiParam(name = "body",value = "主体内容",required = false)@RequestParam(value = "body",required = false)String body,
@ApiParam(name = "filepath",value = "附件",required = false)@RequestParam(value = "filepath",required = false)List<String> filepath) throws Exception{
return emailService.sendEmail(otherCount,chaopSongCount,subject,body,filepath);
}
}
EmailServiceImpl
package com.richfit.richfit.service;
import org.springframework.stereotype.Service;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message;
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 java.util.Date;
import java.util.List;
import java.util.Properties;
/**
* @ClassName EmailServiceImpl
* @Description: 邮件支持发送人多人,多人接收,带附件
* @Author BruthLi
* @Date 2020/2/7
* @Version V1.0
**/
@Service
public class EmailServiceImpl implements EmailService{
// 发件人的 邮箱 和 密码(替换为自己的邮箱和密码)
// PS: 某些邮箱服务器为了增加邮箱本身密码的安全性,给 SMTP 客户端设置了独立密码(有的邮箱称为“授权码”),
// 对于开启了独立密码的邮箱, 这里的邮箱密码必需使用这个独立密码(授权码)。
public static String myEmailAccount = "";
public static String myEmailPassword = "";
// 发件人邮箱的 SMTP 服务器地址, 必须准确, 不同邮件服务器地址不同, 一般(只是一般, 绝非绝对)格式为: smtp.xxx.com
// 网易163邮箱的 SMTP 服务器地址为: smtp.163.com
public static String myEmailSMTPHost = "smtp.163.com";
/**
* 创建一封只包含文本的简单邮件
* @param
* @param
* @param
* @return
* @throws Exception
*/
public Message sendEmail(String otherCount,String chaopSongCount,String subject, String body,List<String>filepath) throws Exception {
if (subject == null) {
subject = "无标题邮件";
}
if (body == null) {
body = "";
}
// 加载配置信息
Properties props = new Properties(); // 参数配置
props.setProperty("mail.transport.protocol", "smtp"); // 使用的协议(JavaMail规范要求)
props.setProperty("mail.smtp.host", myEmailSMTPHost); // 发件人的邮箱的 SMTP 服务器地址
props.setProperty("mail.smtp.auth", "true");
/*MailHandler md = new MailHandler();
Properties prop = md.conf;
String hostName = prop.getProperty("mail.host");
String username = prop.getProperty("mail.username");
String password = prop.getProperty("mail.password");
String from = "service@pjsfax.com"; // 发件人信息*/
// System.out.println("配置信息:" + hostName + "/" + username + "/" + password);
Session session = Session.getInstance(props);
session.setDebug(true);
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(myEmailAccount));
message.setHeader("邮件标题", "Good noon");
MimeMultipart multipart = new MimeMultipart();
// 邮件正文
MimeBodyPart text = new MimeBodyPart();
text.setContent(body, "text/html;charset=UTF-8");
multipart.addBodyPart(text);
// 多个收件人地址
InternetAddress[] addressesTo = null;
if (otherCount != null && otherCount.trim().length() > 0) {
String[] receiveList = otherCount.split(",");
int receiveCount = receiveList.length;
if (receiveCount > 0) {
addressesTo = new InternetAddress[receiveCount];
for (int i = 0; i < receiveCount; i++) {
addressesTo[i] = new InternetAddress(receiveList[i]);
}
}
} else {
System.out.println("None receiver!");
// return false;
}
// 多个抄送人地址
InternetAddress[] addressesCc = null;
if (chaopSongCount != null && chaopSongCount.trim().length() > 0) {
String[] copyList = chaopSongCount.split(",");
int copyCount = copyList.length;
if (copyCount > 0) {
addressesCc = new InternetAddress[copyCount];
for (int i = 0; i < copyCount; i++) {
addressesCc[i] = new InternetAddress(copyList[i]);
}
}
}
//多个附件
if (filepath != null && filepath.size() > 0) {
for (String path : filepath) {
MimeBodyPart bodyPart = new MimeBodyPart();
DataSource dh = new FileDataSource(path);
bodyPart.setDataHandler(new DataHandler(dh));
bodyPart.setFileName(dh.getName());
multipart.addBodyPart(bodyPart);
}
}
message.setContent(multipart);
message.setRecipients(MimeMessage.RecipientType.TO, addressesTo);
message.setRecipients(MimeMessage.RecipientType.CC, addressesCc);
message.setSubject(subject);
message.setSentDate(new Date());
message.saveChanges();
Transport transport = session.getTransport();
transport.connect(myEmailSMTPHost, myEmailAccount, myEmailPassword);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
return message;
}
}
我上面代码是没有开启SSL ,如果开启Properties 替换为如下代码:
// SMTP 服务器的端口 (非 SSL 连接的端口一般默认为 25, 可以不添加, 如果开启了 SSL 连接,
// 需要改为对应邮箱的 SMTP 服务器的端口, 具体可查看对应邮箱服务的帮助,
//QQ邮箱的SMTP(SLL)端口为465或587, 其他邮箱自行去查看)
final String smtpPort = "465";
Properties props = new Properties();
props.setProperty("mail.smtp.port", smtpPort);
props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.socketFactory.port", smtpPort);
如下输入参数: