相關JavaMail的介紹可以參考Java程式Mail、EDM(電子型錄)寄送
最近使用synology架設了mail server,然後利用Let’s Encrypt加載了SSL功能,所以改寫了寄送郵件的程式。
有關synology架mail server部份可以參考
Let’s Encrypt安裝的部份可以由synology自動取得。
JavaMail send Mail程式碼如下
package com.izero.mail.thread;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import com.sun.mail.util.MailSSLSocketFactory;
public class Sender {
private String content;
private org.apache.log4j.Logger log ;
private String subject;
private ArrayList<InternetAddress> to;
private Properties p;
public Sender(ArrayList<InternetAddress> to,String subject,String content,Properties p)
{
super();
this.content = content;
this.to = to;
log = org.apache.log4j.Logger.getLogger(this.getClass());
this.p = p;
this.subject = subject;
}
public void run() {
try {
// 設定傳送基本資訊
String host = p.getProperty("host");
String from = p.getProperty("from");
String user=p.getProperty("user");
String pwd=p.getProperty("pwd");
String port = p.getProperty("port");
Properties props = System.getProperties();
log.info(user);
log.info(pwd);
log.info(from);
log.info("mail.smtp.host="+ host);
log.info("mail.smtp.auth="+ true);
log.info("mail.smtp.port="+ port);
// 設定SMTP server
props.put("mail.smtp.host", host);
props.put("mail.smtp.auth", "true");
//props.put("mail.smtp.port", port);
//props.put("mail.smtp.starttls.enable", true);
//使用ssl或tls連線
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
props.put("mail.imap.ssl.trust", "*");
props.put("mail.imap.ssl.socketFactory", sf);
//認證
Authenticator auth = new SMTPAuthenticator(user,pwd);
// 依據Properties建立一個Session
Session mailSession = Session.getInstance(props, auth);
// 從Session建立一個Message
/*Message mailMessage = new MimeMessage(mailSession);
// Set from email address
mailMessage.setFrom(new InternetAddress(from));
// Set to mail address
mailMessage.setRecipient(Message.RecipientType.TO,
new InternetAddress(to));
// 設定標題
mailMessage.setSubject("Hello JavaMail");
// 設定Mail內容
mailMessage.setText("Wellcome to JavaMail...加油!!");*/
MimeMessage message = new MimeMessage(mailSession);
message.setFrom(new InternetAddress(from,p.getProperty("fromName","big5")));
// System.out.println(p.getProperty("fromName","utf-8"));
/*new InternetAddress(
to)*/
for(int i = 0 ; i < to.size();i++)
message.addRecipient(Message.RecipientType.TO, to.get(i));
// 加入標題
message.setSubject(this.subject);
message.setSentDate(new Date());
// 向multipart增加個別內容body
Multipart multipart = new MimeMultipart();
//設定內容本文
BodyPart contentPart = new MimeBodyPart();
//Multi
contentPart.setContent(content,"text/plain;charset=big5");//給BodyPart對像設置內容和格式/編碼方式
//純文字內容
//contentPart.setText(content);
multipart.addBodyPart(contentPart);
// 增加附件
// BodyPart messageBodyPart = new MimeBodyPart();
// DataSource source = new FileDataSource(affix);
// 增加附件的内容
// messageBodyPart.setDataHandler(new DataHandler(source));
// 附件標題
// 使用base64編碼,讓傳送過程內容不會變亂碼
// sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
// messageBodyPart.setFileName(MimeUtility.encodeText(filename,"BIG5","B"));
// multipart.addBodyPart(messageBodyPart);
// 將multipart放到message中
message.setContent(multipart);
// 保存郵件
message.saveChanges();
Transport transport = mailSession.getTransport("smtp");
// 傳送
transport.connect(host, user, pwd);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
log.info(to+",寄送完成");
//Transport.send(mailMessage);
//System.out.println("\n Mail was sent successfully.");
} catch (Exception e) {
log.info(this.to+"-"+e.getMessage());
e.printStackTrace();
}
}
private class SMTPAuthenticator extends javax.mail.Authenticator {
private String SMTP_AUTH_PWD;
private String SMTP_AUTH_USER;
public SMTPAuthenticator(String SMTP_AUTH_USER,String SMTP_AUTH_PWD)
{
super();
this.SMTP_AUTH_USER = SMTP_AUTH_USER;
this.SMTP_AUTH_PWD = SMTP_AUTH_PWD;
}
public PasswordAuthentication getPasswordAuthentication() {
String username = SMTP_AUTH_USER;
String password = SMTP_AUTH_PWD;
System.out.println(SMTP_AUTH_USER+";"+SMTP_AUTH_PWD);
return new PasswordAuthentication(username, password);
}
}
}
測試的source
public static void main(String args[])throws Exception
{
ArrayList<InternetAddress> to = new ArrayList<InternetAddress>();
if(args.length==0)
{
to.add(new InternetAddress("yku@mailserver"));
}else
{
for(int i = 0 ; i < args.length;i++)
to.add(new InternetAddress(args[i]));
}
Properties p= new Properties();
//log.info((new java.io.File("mail.properties")).getAbsoluteFile());
System.out.println((new java.io.File("mail.properties")).getAbsoluteFile());
java.io.FileReader fr = new java.io.FileReader("mail.properties");
java.io.BufferedReader br = new java.io.BufferedReader(fr);
String str;
while((str=br.readLine())!=null)
{
String[] tmp = str.split("=");
p.setProperty(tmp[0], tmp[1]);
}
br.close();
fr.close();
com.izero.mail.thread.Sender sender = new com.izero.mail.thread.Sender(to,"測試信件","內容如下:",p);
sender.run();
//new Main(to);
}
設定檔內容範例
host=smtp.mailserver port=587 from=yku@mailserver auth=true user=yku pwd=password fromName=顯示寄送者為誰