常見錯誤:
1.關於使用Java Mail進行郵件發送,拋出Could not connect to SMTP host: [email protected], port: 25的異常
2.使用 JavaMailSenderImpl SSL 465 發送郵件
3.java.net.SocketTimeoutException: Read timed out的解決辦法
加密與非加密配置方式
1.簡單郵件非ssl使用25端口的STMP郵件
public class MailMessageSchedule {
public void mailMessage()throws Exception {
JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();
System.setProperty("java.net.preferIPv4Stack", "true");
//設定mail server
senderImpl.setHost("smtp.qq.com");
MimeMessage mailMessage = senderImpl.createMimeMessage();
MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage,true,"utf-8"); messageHelper.addAttachment(fileName,file);
//收件人
messageHelper.setTo([email protected]);
//發件人
messageHelper.setFrom("[email protected]");
//設置郵件標題
messageHelper.setSubject(“標題”);
//設置郵件內容,true表示開啓HTML文本格式
messageHelper.setText(content,true);
//這是發件人郵箱信息,username表示用戶郵箱,password表示對應郵件授權碼
senderImpl.setUsername("[email protected]") ;
senderImpl.setPassword("授權碼") ;
Properties prop = new Properties() ;
prop.put("mail.smtp.auth", "true") ; // 將這個參數設爲true,讓服務器進行認證,認證用戶名和密碼是否正確
prop.put("mail.smtp.timeout", "25000") ;
senderImpl.setJavaMailProperties(prop);
//發送郵件
senderImpl.send(mailMessage);
System.out.println("郵件發送成功..");
}
}
2.加密郵件開啓ssl使用465端口:
public class MailMessageSchedule {
public void mailMessage()throws Exception {
JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();
System.setProperty("java.net.preferIPv4Stack", "true");
//設定mail server
senderImpl.setHost("smtp.qq.com");
MimeMessage mailMessage = senderImpl.createMimeMessage();
MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage,true,"utf-8"); messageHelper.addAttachment(fileName,file);
//收件人
messageHelper.setTo([email protected]);
//發件人
messageHelper.setFrom("[email protected]");
//設置郵件標題
messageHelper.setSubject(“標題”);
//設置郵件內容,true表示開啓HTML文本格式
messageHelper.setText(content,true);
//這是發件人郵箱信息,username表示用戶郵箱,password表示對應郵件授權碼
senderImpl.setUsername("[email protected]") ;
senderImpl.setPassword("授權碼") ;
//開啓ssl
Properties properties = new Properties();
properties.setProperty("mail.smtp.auth", "true");//開啓認證
properties.setProperty("mail.debug", "true");//啓用調試
properties.setProperty("mail.smtp.timeout", "200000");//設置鏈接超時
properties.setProperty("mail.smtp.port", Integer.toString(25));//設置端口
properties.setProperty("mail.smtp.socketFactory.port", Integer.toString(465));//設置ssl端口
properties.setProperty("mail.smtp.socketFactory.fallback", "false");
properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
senderImpl.setJavaMailProperties(properties);
//發送郵件
senderImpl.send(mailMessage);
System.out.println("郵件發送成功..");
}
}
代碼示例
1.帶附件的簡單郵件:
package com.thon.task;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.Properties;
/**
* @description 帶附件郵件發送
**/
public class FileMail {
public static void main(String[] args) throws Exception{
JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();
//設定mail server
senderImpl.setHost("smtp.qq.com");
//建立郵件消息,發送簡單郵件和html郵件的區別
MimeMessage mailMessage = senderImpl.createMimeMessage();
//注意這裏的boolean,等於真的時候才能嵌套圖片,在構建MimeMessageHelper時候,所給定的值是true表示啓用,
//multipart模式 爲true時發送附件 可以設置html格式
MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage,true,"utf-8");
//設置收件人,寄件人
messageHelper.setTo("[email protected]");
messageHelper.setFrom("[email protected]");
messageHelper.setSubject("測試郵件中上傳附件!");
//true 表示啓動HTML格式的郵件
messageHelper.setText("這是內容",true);
FileSystemResource file = new FileSystemResource(new File("E:\\新建文件夾 (2)\\ysg.gif"));
//這裏的方法調用和插入圖片是不同的。
messageHelper.addAttachment("藥水哥.gif",file);
senderImpl.setUsername("[email protected]") ; // 根據自己的情況,設置username
senderImpl.setPassword("授權碼") ; // 根據自己的情況, 設置password
Properties prop = new Properties() ;
prop.put("mail.smtp.auth", "true") ; // 將這個參數設爲true,讓服務器進行認證,認證用戶名和密碼是否正確
prop.put("mail.smtp.timeout", "25000") ;
senderImpl.setJavaMailProperties(prop);
//發送郵件
senderImpl.send(mailMessage);
System.out.println("郵件發送成功..");
}
}
2.支持HTML樣式的文本郵件
package com.thon.task;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
/**
* @description 文本郵件發送
**/
public class HtmlMail {
public static void main(String[] args) throws Exception{
JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();
//設定mail server
senderImpl.setHost("smtp.qq.com");
//建立郵件消息,發送簡單郵件和html郵件的區別
MimeMessage mailMessage = senderImpl.createMimeMessage();
//注意這裏的boolean,等於真的時候才能嵌套圖片,在構建MimeMessageHelper時候,所給定的值是true表示啓用,
//multipart模式 爲true時發送附件 可以設置html格式
MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage);
//設置收件人,寄件人
messageHelper.setTo("[email protected]");
messageHelper.setFrom("[email protected]");
messageHelper.setSubject("測試郵件中上傳附件112!!"); //郵件標題
//true 表示啓動HTML格式的郵件
messageHelper.setText("<html><head></head><body><h1>你好:附件中有學習資料!</h1></body></html>",true);
senderImpl.setUsername("[email protected]") ; // 根據自己的情況,設置username
senderImpl.setPassword("授權碼") ; // 根據自己的情況, 設置password
Properties prop = new Properties() ;
prop.put("mail.smtp.auth", "true") ; // 將這個參數設爲true,讓服務器進行認證,認證用戶名和密碼是否正確
prop.put("mail.smtp.timeout", "25000") ;
senderImpl.setJavaMailProperties(prop);
//發送郵件
senderImpl.send(mailMessage);
System.out.println("郵件發送成功..");
}
}
3.帶圖片的簡單郵件
package com.thon.task;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.Properties;
/**
* @description 內嵌圖片郵件發送
**/
public class ImageMail {
public static void main(String[] args) throws Exception{
JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();
//設定mail server
senderImpl.setHost("smtp.qq.com");
//建立郵件消息,發送簡單郵件和html郵件的區別
MimeMessage mailMessage = senderImpl.createMimeMessage();
//注意這裏的boolean,等於真的時候才能嵌套圖片,在構建MimeMessageHelper時候,所給定的值是true表示啓用,
//multipart模式 爲true時發送附件 可以設置html格式
MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage,true,"utf-8");
//設置收件人,寄件人
messageHelper.setTo("[email protected]");
messageHelper.setFrom("[email protected]");
messageHelper.setSubject("測試圖片郵件!");
//true 表示啓動HTML格式的郵件
messageHelper.setText("<html><head></head><body><h1>hello!!spring image html mail</h1>" +
"<img src=\"cid:aaa\"/></body></html>",true);
FileSystemResource file = new FileSystemResource(new File("/Users/thon/Pictures/漂亮/p2.jpg"));
//插入圖片
messageHelper.addInline("aaa",file);
senderImpl.setUsername("[email protected]") ; // 根據自己的情況,設置username
senderImpl.setPassword("授權碼") ; // 根據自己的情況, 設置password
Properties prop = new Properties() ;
prop.put("mail.smtp.auth", "true") ; // 將這個參數設爲true,讓服務器進行認證,認證用戶名和密碼是否正確
prop.put("mail.smtp.timeout", "25000") ;
senderImpl.setJavaMailProperties(prop);
//發送郵件
senderImpl.send(mailMessage);
System.out.println("郵件發送成功..");
}
}
4.使用ssl加密發送帶附件的html郵件:
package com.thon.schedule;
/**
* Created by hucong on 2019-05-30.
* 招標郵件
*/
import com.thon.commons.utils.StringUtils;
import com.thon.entity.system.Attachment;
import com.thon.model.BidMail;
import com.thon.model.BidPost;
import com.thon.model.BidPostSign;
import com.thon.service.system.AttachmentService;
import com.thon.service.utils.AttachmentUtil;
import com.thon.service.wzgl.BidMailService;
import com.thon.service.wzgl.BidPostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import javax.mail.internet.MimeMessage;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
@Component
public class MailMessageSchedule {
@Autowired
private BidPostService bidPostService;
@Autowired
private BidMailService bidMailService;
@Autowired
private AttachmentService attachmentService;
public void mailMessage()throws Exception {
JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();
System.setProperty("java.net.preferIPv4Stack", "true");
//設定mail server
senderImpl.setHost("smtp.qq.com");
MimeMessage mailMessage = senderImpl.createMimeMessage();
MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage,true,"utf-8");
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date currentTime = df.parse(df.format(new Date()));
//獲取已過截止日期招標記錄
List<BidPost> rbidPosts = bidPostService.selectByDate(currentTime);
//獲取已經發送過的招標信息
List<BidMail> bidMails =bidMailService.selectByDate(currentTime);
List<BidPost> bidPosts = new ArrayList<>(rbidPosts);
for (BidPost p : rbidPosts){
for (BidMail m : bidMails){
if (m.getBidPostId().equals(p.getId())){
bidPosts.remove(p);
}
}
}
//發送郵件
for (BidPost bidPost:bidPosts){
String sendException ="success";
String title = "詢價招標通知函";
String content = new String();
String table = new String();
for (BidPostSign s : bidPost.getOffers()){
//供應商信息
table += "<tr>" +
"<td>"+s.getSupplierName()+"</td>" +
"<td>"+s.getSupplierCode()+"</td>" +
"<td>"+s.getLinkman()+"</td>" +
"<td>"+s.getPhone()+"</td>" +
"<td>"+(s.getSubmitDate()==null?"未填寫日期":df.format(s.getSubmitDate()))+"</td>" +
"<td>"+(s.getApplyDate()==null?"未填寫日期":df.format(s.getApplyDate()))+"</td>" +
"</tr>" ;
//供應商投標附件
try
{
if (!StringUtils.isNotBlank(s.getSubmitFiles())){
break;
}
Attachment attachment = attachmentService.getAttachment(Integer.valueOf(s.getSubmitFiles()));
if (attachment == null) {
attachment = new Attachment();
}
AttachmentUtil.read(attachment);
byte[] bytes = attachment.getBytes();
String fileName = URLEncoder.encode(attachment.getFileName(), "UTF-8");
String path = "/data/.material/tmp/"+"【投標文件】"+"【"+s.getSupplierName()+"】"+fileName;
// 根據絕對路徑初始化文件
File localFile = new File(path);
//判斷文件父目錄是否存在
if (!localFile.getParentFile().exists()){
localFile.getParentFile().mkdir();
}
if (!localFile.exists())
{
localFile.createNewFile();
}
// 輸出流
OutputStream os = new FileOutputStream(localFile);
os.write(bytes);
os.close();
messageHelper.addAttachment("【投標文件】"+"【"+s.getSupplierName()+"】"+fileName,localFile);
}
catch (Exception e)
{
e.printStackTrace();
bidMailService.save(bidPost,"file_read_error_submit:"+s.getId());
}
//供應商申請報價附件
try
{
if (!StringUtils.isNotBlank(s.getApplyFiles())){
break;
}
Attachment attachment = attachmentService.getAttachment(Integer.valueOf(s.getApplyFiles()));
if (attachment == null) {
attachment = new Attachment();
}
AttachmentUtil.read(attachment);
byte[] bytes = attachment.getBytes();
String fileName = URLEncoder.encode(attachment.getFileName(), "UTF-8");
String path = "/data/.material/tmp/"+"【申請報價】"+"【"+s.getSupplierName()+"】"+fileName;
// 根據絕對路徑初始化文件
File localFile = new File(path);
if (!localFile.exists())
{
localFile.createNewFile();
}
// 輸出流
OutputStream os = new FileOutputStream(localFile);
os.write(bytes);
os.close();
messageHelper.addAttachment("【申請報價】"+"【"+s.getSupplierName()+"】"+fileName,localFile);
}
catch (Exception e)
{
e.printStackTrace();
bidMailService.save(bidPost,"file_read_error_apply:"+s.getId());
}
}
//設置收件人,寄件人
if (bidPost.getEmails()!=null){
//多郵箱用','分割
String[] emails = bidPost.getEmails().split(",");
messageHelper.setTo(emails);
}
else {
bidMailService.save(bidPost,"email_error:"+bidPost.getEmails());
return;
}
messageHelper.setFrom("[email protected]");
messageHelper.setSubject(title);
//true 表示啓動HTML格式的郵件
content="<p>採購信息發佈標題:"+bidPost.getTitle()+" </p>" +
"<p>採購分類:"+bidPost.getPriceType()+"</p>" +
"<p>詢價編號:"+bidPost.getCode()+"</p>" +
"<p>申請單位:"+bidPost.getOfficeName()+"</p>" +
"<p>發佈者:"+bidPost.getAuthor()+"</p>" +
"<p>發佈日期:"+df.format(bidPost.getCreatedDate())+"</p>" +
"<p>截止日期:"+df.format(bidPost.getDeadlineDate())+"</p>" +
"<p><br /></p>" +
"<p><span id=\"__kindeditor_bookmark_start_10__\">" +
"<table style=\"width:100%;\" cellpadding=\"2\" cellspacing=\"0\" border=\"1\" bordercolor=\"#000000\">\n" +
"<tbody>" +
"<tr>" +
"<td>供應商名稱</td>" +
"<td>組織機構</td>" +
"<td>聯繫人</td>" +
"<td>手機號</td>" +
"<td>報價時間</td>" +
"<td>申請報價時間</td>" +
"</tr>" +
table +
"</tbody>" +
"</table>" +
"<br />" +
"<span id=\"__kindeditor_bookmark_start_90__\"></span>附件:<br />" +
"<br />" +
"</span>" +
"</p>";
messageHelper.setText(content,true);
senderImpl.setUsername("[email protected]") ;
senderImpl.setPassword("授權碼") ;
//開啓ssl
Properties properties = new Properties();
properties.setProperty("mail.smtp.auth", "true");//開啓認證
properties.setProperty("mail.debug", "true");//啓用調試
properties.setProperty("mail.smtp.timeout", "200000");//設置鏈接超時
properties.setProperty("mail.smtp.port", Integer.toString(25));//設置端口
properties.setProperty("mail.smtp.socketFactory.port", Integer.toString(465));//設置ssl端口
properties.setProperty("mail.smtp.socketFactory.fallback", "false");
properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
senderImpl.setJavaMailProperties(properties);
senderImpl.send(mailMessage);
bidMailService.save(bidPost,sendException);
System.out.println("郵件發送成功..");
System.out.println("定時器啓動!");
}
}
}