String str = "我喜欢你,世界";
邮件
依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
application/yml
mail.config.SMTP_host=smtp.qq.com
mail.config.SMTP_port=25 #端口号,一般有ssl的时候端口号是其他的
mail.config.SMTP_auth=true #连接校验
mail.config.STMP_user=xxxx@qq.com #发件人用户
mail.config.STMP_pass=xxxxx #授权码
mail.config.SMTP_from=2428202862@qq.com #发件人
mail.config.SMTP_fromnick=xxx对方邮箱显示的不是qq号而是nickname
配置类
package lut.mail;
public class MailConfig {
private String SMTP_host;
private int SMTP_port;
private boolean SMTP_auth;
private String STMP_user;
private String STMP_pass;
private String SMTP_from;
private String SMTP_fromnick;
getter/setter......
}
配置类注入
package lut.mail;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MailConfiguration {
@Value("${mail.config.SMTP_host}")
private String SMTP_host;
@Value("${mail.config.SMTP_port}")
private int SMTP_port;
@Value("${mail.config.SMTP_auth}")
private boolean SMTP_auth;
@Value("${mail.config.STMP_user}")
private String STMP_user;
@Value("${mail.config.STMP_pass}")
private String STMP_pass;
@Value("${mail.config.SMTP_from}")
private String SMTP_from;
@Value("${mail.config.SMTP_fromnick}")
private String SMTP_fromnick;
@Bean
public MailConfig getmailConfig(){
MailConfig mc = new MailConfig();
mc.setSMTP_host(SMTP_host);
mc.setSMTP_port(SMTP_port);
mc.setSMTP_auth(SMTP_auth);
mc.setSTMP_user(STMP_user);
mc.setSTMP_pass(STMP_pass);
mc.setSMTP_from(SMTP_from);
mc.setSMTP_fromnick(SMTP_fromnick);
return mc;
}
}
实现Authenticator抽象类(此类做session实例化是会用到)
package lut.mail;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
public class MailSMTPAuthenticator extends Authenticator{
private String sName;
private String sPassword;
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(sName, sPassword);
}
public String getsName() {
return sName;
}
public void setsName(String sName) {
this.sName = sName;
}
public String getsPassword() {
return sPassword;
}
public void setsPassword(String sPassword) {
this.sPassword = sPassword;
}
}
邮件功能实现
package lut.mail;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
@SuppressWarnings("unused")
public class MailService {
@Autowired
private MailConfig mailconfig;
public void senMail(){
System.out.println(mailconfig.toString());
MimeMessage mMessage = null;
Session mailSession = null;
//1、连接邮件服务器的参数配置附件名称过长乱码解决,关键词false
System.setProperty("mail.mime.splitlongparameters","false");
Properties props = new Properties();
props.setProperty("mail.smtp.host", mailconfig.getSMTP_host());
props.setProperty("mail.smtp.port", mailconfig.getSMTP_port()+"");
props.setProperty("mail.smtp.auth", mailconfig.getSMTP_auth()+"");
// 设置SMTP连接和发送邮件的超时时间,因为缺省是无限超时,单位毫秒
props.setProperty("mail.smtp.connectiontimeout", "15000");//SMTP服务器连接超时时间
props.setProperty("mail.smtp.timeout","60000");//发送邮件超时时间
if(mailconfig.getSMTP_auth()){
MailSMTPAuthenticator smtpAutr= new MailSMTPAuthenticator();
smtpAutr.setsName(mailconfig.getSTMP_user());
smtpAutr.setsPassword("sunwei951025");
mailSession = Session.getInstance(props, smtpAutr);
}else{
mailSession = Session.getInstance(props);
}
mailSession.setDebug(true);
mMessage = new MimeMessage(mailSession);
try {
//发件人
InternetAddress formAddress = new InternetAddress(mailconfig.getSMTP_from());
formAddress.setPersonal("了然于心");
mMessage.setFrom(formAddress);
//发送时间
mMessage.setSentDate(new Date());
//收件人
InternetAddress[] toAddress = {new InternetAddress("sunw@hrocloud.com"),new InternetAddress("sunwei1995sh@126.com")};
mMessage.setRecipients(Message.RecipientType.TO,toAddress);
//主题
mMessage.setSubject("孙维主题");
//内容
MimeBodyPart contentBodyPart = new MimeBodyPart();
contentBodyPart.setContent("此邮件为系统自己主动发送<img src='cid:a'><img src='cid:a'>","text/html;charset=UTF-8"); //cid必须和相关图片的ContentID相同才会在邮件正文显示图片。//图片 MimeBodyPart imgAff = new MimeBodyPart(); imgAff.setDataHandler(new DataHandler(new FileDataSource("d:\\IO.jpg"))); imgAff.setContentID("a"); MimeMultipart addM = new MimeMultipart(); addM.addBodyPart(contentBodyPart); addM.addBodyPart(imgAff); addM.setSubType("related"); // 图班与正文的 body MimeBodyPart affContent = new MimeBodyPart(); affContent.setContent(addM); //附件MimeBodyPart affDoc = new MimeBodyPart(); affDoc.setDataHandler(new DataHandler(new FileDataSource("d:\\业务流程脚本.sql"))); affDoc.setFileName(MimeUtility.encodeText("业务流程脚本.sql")); affDoc.setContentID("UUud"); MimeMultipart text = new MimeMultipart(); text.addBodyPart(affContent); text.addBodyPart(affDoc); text.setSubType("mixed"); mMessage.setContent(text); mMessage.saveChanges(); Transport transport = null; transport = mailSession.getTransport("smtp"); transport.connect(mailconfig.getSTMP_user(),mailconfig.getSTMP_pass()); transport.sendMessage(mMessage, mMessage.getAllRecipients()); transport.close(); } catch (MessagingException | UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-CpRKu0JU-1600006971877)(C:\Users\Administrator\Desktop\repot\readme.assets\1323426-20191212164549529-545357524.png)]
邮件实现2
一般是这样的,我们可能不会要求马上发送这封邮件,为了减少服务器压力和带宽压力,我们一般是在空闲时在发送,或者用户指定时间才发送
那么就要先把邮件进行保存,然后按时发送
可以将信息保存到数据库,然后获取后再组装邮件信息,这里我们就把邮件打成一个文件保存在本地
保存到本地很简单,只要之前你的示例都能跑通,只差一步
这里就不再一一的解说了!
package com.mail;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
/**
* @说明 保存一个邮件
* @author cuisuqiang
* @version 1.0
* @since
*/
public class TextMail {
public static void main(String[] args) throws Exception {
Properties props = new Properties();
props.put( "mail.smtp.host ", "smtp.163.com ");
props.put("mail.smtp.port", 25);
props.put("mail.smtp.auth", "true");
Session session = Session.getInstance(props);
session.setDebug(true);
Message message = new MimeMessage(session);
InternetAddress from = new InternetAddress("test20120711120200@163.com");
from.setPersonal(MimeUtility.encodeText("java小强<test20120711120200@163.com>"));
message.setFrom(from);
InternetAddress to = new InternetAddress("test20120711120200@163.com");
message.setRecipient(Message.RecipientType.TO, to);
message.setSubject(MimeUtility.encodeText("强哥邀请,谁敢不从!"));
message.setText("强哥邀请你访问我的博客:http://cuisuqiang.iteye.com/");
message.setSentDate(new Date());
// 邮件对象
File file = new File("C:\\textmail.eml");
// 获得输出流
OutputStream ips = new FileOutputStream(file);
// 把邮件内容写入到文件
message.writeTo(ips);
// 关闭流
ips.close();
System.out.println("发送完毕");
}
}
邮件对象创建后没有立即发送,而是保存到了一个文件中
那么如何发送一封已经存在的邮件呢?也很简单,只是邮件对象的创建的方式不一样了而已
package com.mail;
import java.io.File;
import java.io.FileInputStream;
import java.util.Date;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.MimeMessage;
/**
* 放松一封现有邮件
* @author cuisuqiang@163.com
*/
public class SendCurrentMail {
public static void main(String[] args) throws Exception {
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
Session session = Session.getInstance(props);
// 现有邮件文件
File file = new File("C:\\textmail.eml");
FileInputStream fis = new FileInputStream(file);
// 创建邮件对象
Message message = new MimeMessage(session, fis);
message.setSentDate(new Date());
message.saveChanges();
// 发送邮件
Transport transport = session.getTransport("smtp");
transport.connect("smtp.163.com", 25, "test20120711120200", "test123456");
transport.sendMessage(message, message.getAllRecipients());
transport.close();
fis.close();
System.out.println("发送完毕");
}
}
发送附件
package com.mail;
import java.util.Date;
import java.util.Properties;
import javax.activation.DataHandler;
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 javax.mail.internet.MimeUtility;
public class Html_File_InnerFile {
public static void main(String[] args) throws Exception {
Properties props = new Properties();
props.put( "mail.smtp.host ", "smtp.163.com ");
props.put("mail.smtp.auth", "true");
Session session = Session.getInstance(props);
Message message = new MimeMessage(session);
InternetAddress from = new InternetAddress("test20120711120200@163.com");
from.setPersonal(MimeUtility.encodeText("风中落叶<test20120711120200@163.com>"));
message.setFrom(from);
InternetAddress to = new InternetAddress("test20120711120200@163.com");
message.setRecipient(Message.RecipientType.TO, to);
message.setSubject(MimeUtility.encodeText("强哥邀请,谁敢不从!"));
message.setSentDate(new Date());
MimeMultipart msgMultipart = new MimeMultipart("mixed");// 指定为混合关系
message.setContent(msgMultipart);
// 邮件内容
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(
"<body background='http://dl.iteye.com/upload/picture/pic/110267/e244bda9-9034-36e3-87fd-807629b84222.jpg'>"
+ "<div style='position: absolute; left: 390px; top: 150px;height: "
+ "100px;width: 200px;' align='center'>"
+ "<font color='red'>这是测试邮件,请勿回复</font>" + "</div></body>",
"text/html;charset=UTF-8");
// TODO 组装的顺序非常重要,一定要先组装文本域,再组装文件
msgMultipart.addBodyPart(htmlPart);
// 组装附件
MimeBodyPart file = new MimeBodyPart();
FileDataSource file_datasource = new FileDataSource("D:\\img201008031058340.zip");
DataHandler dh = new DataHandler(file_datasource);
file.setDataHandler(dh);
// 附件区别内嵌内容的一个特点是有文件名,为防止中文乱码要编码
file.setFileName(MimeUtility.encodeText(dh.getName()));
msgMultipart.addBodyPart(file);
message.saveChanges();
Transport transport = session.getTransport("smtp");
transport.connect("smtp.163.com", 25, "test20120711120200", "test123456");
transport.sendMessage(message, message.getAllRecipients());
transport.close();
System.out.println("发送完毕");
}
}
.addBodyPart(file);
message.saveChanges();
Transport transport = session.getTransport(“smtp”);
transport.connect(“smtp.163.com”, 25, “test20120711120200”, “test123456”);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
System.out.println(“发送完毕”);
}
}
```javascript
package com.cy.demo.service;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class TestMain {
public static void main(String[] args) throws Exception {
Session session = Session.getDefaultInstance(new Properties());
MimeMessage message = new MimeMessage(session);
// 发件人
message.setFrom(new InternetAddress("809490705@qq.com"));
// 收件人
String s = "809490705@qq.com;88997766@qq.com;12378954@qq.com";
Address[] to = getAddresses(s);
message.setRecipients(Message.RecipientType.TO, to);
// 主题
message.setSubject("主题报告");
// 内容
String body = "sd;fsjfsl;fj s;a ls;j k;s fj;s aa";
message.setText(body);
//MimeBodyPart content = createContent(body, "filename");
MimeBodyPart attachment = createAttachment("D:\\mail\\mail.txt");
MimeMultipart multipart = new MimeMultipart("mixed");
//multipart.addBodyPart(content);
multipart.addBodyPart(attachment);
message.setContent(multipart);
message.saveChanges();
message.writeTo(new FileOutputStream("D:\\mail\\ComplexMessage.eml"));
}
private static MimeBodyPart createAttachment(String filename) throws Exception {
//创建保存附件的MimeBodyPart对象,并加入附件内容和相应信息
MimeBodyPart attachPart = new MimeBodyPart();
FileDataSource fds = new FileDataSource(filename);
attachPart.setDataHandler(new DataHandler(fds));
attachPart.setFileName(fds.getName());
return attachPart;
}
private static MimeBodyPart createContent(String body, String filename) throws Exception {
/*创建代表组合MIME消息的MimeMultipart对象,
* 和将该MimeMultipart对象保存到MimeBodyPart对象
*/
MimeBodyPart contentPart = new MimeBodyPart();
MimeMultipart contentMultipart = new MimeMultipart("related");
/*创建用于保存HTML正文的MimeBodyPart对象,
* 并将它保存到MimeMultipart中
*/
// MimeBodyPart htmlBodyPart = new MimeBodyPart();
// htmlBodyPart.setContent(body, "text/html;charset=gb2312");
// contentMultipart.addBodyPart(htmlBodyPart);
/*创建用于保存图片的MimeBodyPart对象,
* 并将它保存到MimeMultipart中
*/
// MimeBodyPart gifBodyPart = new MimeBodyPart();
// FileDataSource fds = new FileDataSource(filename);
// gifBodyPart.setDataHandler(new DataHandler(fds));
// gifBodyPart.setContentID("test_img");
// contentMultipart.addBodyPart(gifBodyPart);
//将MimeMultipart对象保存到MimeBodyPart对象中
contentPart.setContent(contentMultipart);
return contentPart;
}
private static Address[] getAddresses(String s) throws AddressException {
String[] strs = s.split(";");
ArrayList<String> list = new ArrayList<>();
for (String str : strs) {
list.add(str);
}
InternetAddress[] addresses = new InternetAddress[list.size()];
for (int i = 0; i <list.size(); i++) {
addresses[i]=new InternetAddress(list.get(i));
}
return addresses;
}
}