邮箱第一种
1.html
<h3>发送邮件</h3>
<form action="/eail/eail/eail" method="post">
<table>
<tr>
<td>主题:<span style="color: red">(*)</span><input type="text" name="subject"></td>
</tr>
<tr>
<td>内容:<span style="color: red">(*)</span><textarea type="text" name="content" ></textarea></td>
</tr>
<tr>
<td>收件人邮箱:<span style="color: red">(*)</span><input type="text" name="T">@qq.com</td>
</tr>
<tr>
<td>抄送邮箱:<input type="text" name="C">@qq.com</td>
</tr>
</table>
<input type="submit" id="tijiao" value="提交"><input type="button" value="返回" onclick="back()">
</form>
2.Controller
package com.bootdo.inventory.controller;
import com.bootdo.common.utils.R;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@RequestMapping("/eail/eail")
@Controller
public class TestController extends EmailTest{
@GetMapping()
public String eail (){
return "inventory/email/eail";
}
@PostMapping("/eail")
public String email (String subject,String content,String T,String C){
EmailTest mail = new EmailTest();
mail.setSubject(subject);
mail.setContent(content);
mail.setFileList(new String[]{"file\\a1.png"});
String F = T+"@qq.com";
if(C.length() > 1){
String G = C+"@qq.com";
mail.setCc(new String[]{G,G});
}
mail.setTo(new String[]{F,F});
try {
mail.sendMessage();
System.out.println("发送邮件成功!");
} catch (Exception e) {
System.out.println("发送邮件失败!");
e.printStackTrace();
}
if(T!=null){
return "inventory/email/eail";
}else{
return "inventory/email/eail";
}
}
}
3.邮件发送的controller继承了工具类EmailTest(TestController extends EmailTest)
package com.bootdo.inventory.controller;
import java.io.UnsupportedEncodingException;
import java.util.*;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.Message.RecipientType;
import javax.mail.internet.*;
public class EmailTest {
// dtpdnilkcpwwebjg
//发送的邮箱 内部代码只适用qq邮箱
private static final String USER = "1025738547@qq.com";
//授权密码 通过QQ邮箱设置->账户->POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务->开启POP3/SMTP服务获取
private static final String PWD = "jlufawhdocwzbbgc";
private String[] to;
private String[] cc;//抄送
private String[] bcc;//密送
private String[] fileList;//附件
private String subject;//主题
private String content;//内容,可以用html语言写
public void sendMessage() throws MessagingException, UnsupportedEncodingException {
// 配置发送邮件的环境属性
final Properties props = new Properties();
//下面两段代码是设置ssl和端口,不设置发送不出去。
props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
//props.setProperty("mail.smtp.port", "465");
props.setProperty("mail.smtp.socketFactory.port", "465");
// 表示SMTP发送邮件,需要进行身份验证
props.setProperty("mail.transport.protocol", "smtp");// 设置传输协议
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", "smtp.qq.com");//QQ邮箱的服务器 如果是企业邮箱或者其他邮箱得更换该服务器地址
// 发件人的账号
props.put("mail.user", USER);
// 访问SMTP服务时需要提供的密码
props.put("mail.password", PWD);
// 构建授权信息,用于进行SMTP进行身份验证
Authenticator authenticator = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
// 用户名、密码
String userName = props.getProperty("mail.user");
String password = props.getProperty("mail.password");
return new PasswordAuthentication(userName, password);
}
};
// 使用环境属性和授权信息,创建邮件会话
Session mailSession = Session.getInstance(props, authenticator);
// 创建邮件消息
MimeMessage message = new MimeMessage(mailSession);
BodyPart messageBodyPart = new MimeBodyPart();
Multipart multipart = new MimeMultipart();
// 设置发件人
InternetAddress form = new InternetAddress(
props.getProperty("mail.user"));
message.setFrom(form);
//发送
if (to != null) {
String toList = getMailList(to);
InternetAddress[] iaToList = new InternetAddress().parse(toList);
message.setRecipients(RecipientType.TO, iaToList); // 收件人
}
//抄送
if (cc != null) {
String toListcc = getMailList(cc);
InternetAddress[] iaToListcc = new InternetAddress().parse(toListcc);
message.setRecipients(RecipientType.CC, iaToListcc); // 抄送人
}
//密送
if (bcc != null) {
String toListbcc = getMailList(bcc);
InternetAddress[] iaToListbcc = new InternetAddress().parse(toListbcc);
message.setRecipients(RecipientType.BCC, iaToListbcc); // 密送人
}
message.setSentDate(new Date()); // 发送日期 该日期可以随意写,你可以写上昨天的日期(效果很特别,亲测,有兴趣可以试试),或者抽象出来形成一个参数。
message.setSubject(subject); // 主题
message.setText(content); // 内容
//显示以html格式的文本内容
messageBodyPart.setContent(content,"text/html;charset=utf-8");
multipart.addBodyPart(messageBodyPart);
//保存多个附件
if(fileList!=null){
addTach(fileList, multipart);
}
message.setContent(multipart);
// 发送邮件
Transport.send(message);
}
public void setTo(String[] to) {
this.to = to;
}
public void setCc(String[] cc) {
this.cc = cc;
}
public void setBcc(String[] bcc) {
this.bcc = bcc;
}
public void setSubject(String subject) {
this.subject = subject;
}
public void setContent(String content) {
this.content = content;
}
public void setFileList(String[] fileList) {
this.fileList = fileList;
}
private String getMailList(String[] mailArray) {
StringBuffer toList = new StringBuffer();
int length = mailArray.length;
if (mailArray != null && length < 2) {
toList.append(mailArray[0]);
} else {
for (int i = 0; i < length; i++) {
toList.append(mailArray[i]);
if (i != (length - 1)) {
toList.append(",");
}
}
}
return toList.toString();
}
//添加多个附件
public void addTach(String fileList[], Multipart multipart)
throws MessagingException, UnsupportedEncodingException {
for (int index = 0; index < fileList.length; index++) {
MimeBodyPart mailArchieve = new MimeBodyPart();
FileDataSource fds = new FileDataSource(fileList[index]);
mailArchieve.setDataHandler(new DataHandler(fds));
mailArchieve.setFileName(MimeUtility.encodeText(fds.getName(),"UTF-8","B"));
multipart.addBodyPart(mailArchieve);
}
}
//以下是演示demo
public static void main(String args[]) {
EmailTest mail = new EmailTest();
mail.setSubject("Hello World");
mail.setContent("Hello World!");
//收件人 可以发给其他邮箱(163等) 下同
String a = "1413118298";
String b = "@qq.com";
String c = a+b;
// mail.setTo(new String[] {"1171136474@qq.com","1171136474@qq.com"});
// mail.setTo(new String[] {"1354214730@qq.com","1354214730@qq.com"});
// mail.setTo(new String[] {"237710545@qq.com","237710545@qq.com"});
// mail.setTo(new String[] {"154514380@qq.com","154514380@qq.com"});
// mail.setTo(new String[] {"2296212405@qq.com","2296212405@qq.com"});
// mail.setTo(new String[] {"1413118298@qq.com","1413118298@qq.com"});
// mail.setTo(new String[] {"1354214730@qq.com","1354214730@qq.com"});
mail.setTo(new String[] {"3441126418@qq.com","3441126418@qq.com"});
// mail.setTo(new String[] {"1025738547@qq.com","1025738547@qq.com"});
//抄送
mail.setCc(new String[] {c,c});
// mail.setCc(new String[] {"1025738547@qq.com","1025738547@qq.com"});
//密送
// mail.setBcc(new String[] {"xxx@qq.com","xxx@qq.com"});
//发送附件列表 可以写绝对路径 也可以写相对路径(起点是项目根目录)
// mail.setFileList(new String[] {"file\\附件1.txt","file\\附件2.txt"});
mail.setFileList(new String[] {"file\\a1.png","file\\a2.jpg"});
//发送邮件
try {
mail.sendMessage();
System.out.println("发送邮件成功!");
} catch (Exception e) {
System.out.println("发送邮件失败!");
e.printStackTrace();
}
}
}
第二种,可以发附件和图片
1.html
<h2 style="text-align: center">QQ邮箱</h2>
<form action="/mail/sendmail" method="post" enctype="multipart/form-data">
<table id="tableContent" data-mobile-responsive="true">
<tr><td><span>发件人地址:</span></td><td><input type="text" id="senderAddress" name="senderAddress" width="100px" style="float: left"></td></tr><br>
<tr><td><span>收件人地址:</span></td><td><input type="text" id="recipientAddress" name="recipientAddress" width="100px" style="float: left"></td></tr><br>
<tr><td><span>抄送:</span> </td><td> <textarea type="text" id="chaosong" name="chaosong" cols="22" rows="10" style="float: left"></textarea> <span>测试账号:1473879777@qq.com,1413118298@qq.com,1025738547@qq.com</span></td></tr><br>
<tr><td><span>发件人账户名:</span></td><td><input type="text" id="senderAccount" name="senderAccount" width="100px" style="float: left"></td></tr><br>
<tr><td><span>发件人密码:</span></td><td><input type="text" id="senderPassword" name="senderPassword" width="100px" style="float: left"><span>测试密码:dbgnxubpzponhcfa</span></td> </tr><br>
<tr><td><span>邮件主题:</span></td><td><input type="text" id="theme" name="theme" width="100px" style="float: left"></td></tr><br>
<tr><td> <span>邮件内容:</span></td><td><textarea name="content" id="content" cols="22" rows="10"style="float: left"></textarea></td></tr><br>
<tr><td><span>上传文件1:</span></td><td><input type="file" name="fileIdPicPath" id="fileIdPicPath" width="100px" style="float: left"></td></tr><br>
<tr><td><span>上传文件2:</span></td><td><input type="file" name="fileWorkPic" id="fileWorkPic" width="100px" style="float: left"></td></tr><br>
</table>
<input type="submit" value="发送">
</form>
2.controller
package com.bootdo.marketing.controller;
import com.bootdo.marketing.domain.Mail;
import com.bootdo.marketing.service.SendMailService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.mail.internet.MimeMessage;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;
import java.util.Properties;
import java.util.UUID;
import javax.servlet.http.Part;
@RequestMapping("/mail")
@Controller
public class SendMailsController {
@Autowired
private SendMailService sendMailService;
@GetMapping()
@RequiresPermissions("send:mail")
public String toMail(){
return "marketing/sendMail/mail";
}
@PostMapping("/sendmail")
public String sendmail( String senderAddress,String recipientAddress, String senderAccount, String senderPassword, String theme, String content, String chaosong, HttpServletRequest request) throws MessagingException, IOException, ServletException {
//1、连接邮件服务器的参数配置
Properties props = new Properties();
//设置用户的认证方式
props.setProperty("mail.smtp.auth", "true");
//设置传输协议
props.setProperty("mail.transport.protocol", "smtp");
//设置发件人的SMTP服务器地址
props.setProperty("mail.smtp.host", "smtp.qq.com");
//2、创建定义整个应用程序所需的环境信息的 Session 对象
Session session = Session.getInstance(props);
//设置调试信息在控制台打印出来
session.setDebug(true);
/*
文件上传
*/
String fileName = null;
String photo1 = null;
String photo2 = null;
for (Part part:request.getParts()){
if (part.getName().startsWith("file")) {
String header = part.getHeader("Content-Disposition");
System.out.println("header=====" + header);
// fileName = header.substring(header.indexOf("filename=\''")+10, header.lastIndexOf("\""));
fileName = header.substring(header.lastIndexOf("."), header.length() - 1);
System.out.println("filename=========" + fileName);
String fileName2 = UUID.randomUUID().toString() + fileName;
String filePath = "F:\\1903-3git\\1903_3\\1903_03\\bootdo\\src\\main\\resources\\static\\img" + "\\" + fileName2;
part.write(filePath);
if (header.contains("fileIdPicPath")) {
photo1 = fileName2;
}
if (header.contains("fileWorkPic")) {
photo2 = fileName2;
}
}
}
//创建一封邮件的实例对象
MimeMessage msg = new MimeMessage(session);
//设置发件人地址
try {
msg.setFrom(new InternetAddress(senderAddress));
} catch (MessagingException e) {
e.printStackTrace();
}
/**
* 设置收件人地址(可以增加多个收件人、抄送、密送),即下面这一行代码书写多行
* MimeMessage.RecipientType.TO:发送
* MimeMessage.RecipientType.CC:抄送
* MimeMessage.RecipientType.BCC:密送
*/
//抄送多人
String[]copy = chaosong.split(",");//通过,号隔开
for (String copy2:copy){
msg.setRecipient(MimeMessage.RecipientType.CC,new InternetAddress(copy2));
}
msg.setRecipient(MimeMessage.RecipientType.TO,new InternetAddress(recipientAddress));
//设置邮件主题
msg.setSubject(theme,"UTF-8");
//设置邮件正文
//msg.setContent(content, "text/html;charset=UTF-8");
//设置邮件的发送时间,默认立即发送
msg.setSentDate(new Date());
//创建图片节点
MimeBodyPart image = new MimeBodyPart();
DataHandler dh = new DataHandler(new FileDataSource("F:\\1903-3git\\1903_3\\1903_03\\bootdo\\src\\main\\resources\\static\\img\\"+photo1));//要改的地方
image.setDataHandler(dh);
image.setContentID("image_fairy_tail");
//创建文本节点
MimeBodyPart text = new MimeBodyPart();
text.setContent("这是一张图片<br/><img src='cid:image_fairy_tail'/>", "text/html;charset=UTF-8");
// 7. (文本+图片)设置 文本 和 图片 “节点”的关系(将 文本 和 图片 “节点”合成一个混合“节点”)
MimeMultipart mm_text_image = new MimeMultipart();
mm_text_image.addBodyPart(text);
mm_text_image.addBodyPart(image);
mm_text_image.setSubType("related");
MimeBodyPart text_image = new MimeBodyPart();
text_image.setContent(mm_text_image);
// 9. 创建附件“节点”
MimeBodyPart attachment = new MimeBodyPart();
DataHandler dh2 = new DataHandler(new FileDataSource("F:\\1903-3git\\1903_3\\1903_03\\bootdo\\src\\main\\resources\\static\\img\\"+photo2)); // 读取本地文件
attachment.setDataHandler(dh2); // 将附件数据添加到“节点”
attachment.setFileName(MimeUtility.encodeText(dh2.getName())); // 设置附件的文件名(需要编码)
// 10. 设置(文本+图片)和 附件 的关系(合成一个大的混合“节点” / Multipart )
MimeMultipart mm = new MimeMultipart();
mm.addBodyPart(text_image);
mm.addBodyPart(attachment); // 如果有多个附件,可以创建多个多次添加
mm.setSubType("mixed"); // 混合关系
//设置邮件正文
msg.setContent( mm);
//4、根据session对象获取邮件传输对象Transport
Transport transport = session.getTransport();
//设置发件人的账户名和密码
transport.connect(senderAccount, senderPassword);
//发送邮件,并发送到所有收件人地址,message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人
transport.sendMessage(msg,msg.getAllRecipients());
Mail mail = new Mail();
mail.setChaosong(chaosong);
mail.setContent(content);
mail.setRecipientAddress(recipientAddress);
mail.setSenderAccount(senderAccount);
mail.setSenderAddress(senderAddress);
mail.setSenderPassword(senderPassword);
mail.setTheme(theme);
sendMailService.addMail(mail);
//如果只想发送给指定的人,可以如下写法
//transport.sendMessage(msg, new Address[]{new InternetAddress("xxx@qq.com")});
//5、关闭邮件连接
transport.close();
return "marketing/sendMail/mail";
}
}