程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> Java發送郵件碰到的罕見需求匯總

Java發送郵件碰到的罕見需求匯總

編輯:關於JAVA

Java發送郵件碰到的罕見需求匯總。本站提示廣大學習愛好者:(Java發送郵件碰到的罕見需求匯總)文章只能為提供參考,不一定能成為您想要的結果。以下是Java發送郵件碰到的罕見需求匯總正文


基於SMTP發送一個簡略的郵件

起首,須要一個認證器:

package No001_基於SMTP的文本郵件;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
public class SimpleAuthenticator extends Authenticator {
private String username;
private String password;
public SimpleAuthenticator(String username, String password) {
super();
this.username = username;
this.password = password;
}
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
} 

然後,書寫簡略的發送郵件法式:

package No001_基於SMTP的文本郵件;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SMTPSimpleMail {
public static void main(String[] args) throws AddressException, MessagingException {
/* 必須的信息 */
String SMTP_MAIL_HOST = "smtp.163.com"; // 此郵件辦事器地址,自行去所屬郵件查詢
String EMAIL_USERNAME = "[email protected]";
String EMAIL_PASSWORD = "mypassword";
String TO_EMAIL_ADDRESS = "[email protected]";
/* 辦事器信息 */
Properties props = new Properties();
props.put("mail.smtp.host", SMTP_MAIL_HOST);
props.put("mail.smtp.auth", "true");
/* 創立Session */
Session session = Session.getDefaultInstance(props, new SimpleAuthenticator(EMAIL_USERNAME, EMAIL_PASSWORD));
/* 郵件信息 */
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(EMAIL_USERNAME));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(TO_EMAIL_ADDRESS));
message.setSubject("how to use java mail to send email.(Title)(001)");
message.setText("how to use java mail to send email.(Content)");
// 發送
Transport.send(message);
System.out.println("不是特殊不利,你可以去查收郵件了。");
}
} 

各類收件人、抄送人、機密抄送人,怎樣辦

認證器沿用,略。

其實就是設置、追加多個收件人、抄送人、機密抄送人:

package No002_各類發件人收件人抄送人怎樣辦;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendMailWithMultiPeople {
public static void main(String[] args) throws AddressException, MessagingException, UnsupportedEncodingException {
/* 必須的信息 */
String SMTP_MAIL_HOST = "smtp.163.com"; // 此郵件辦事器地址,自行去所屬郵件查詢
String EMAIL_USERNAME = "[email protected]";
String EMAIL_PASSWORD = "mypassword";
String TO_EMAIL_ADDRESS_1 = "[email protected]";
String CC_EMAIL_ADDRESS_1 = "[email protected]";
String BCC_EMAIL_ADDRESS_1 = "[email protected]";
/* 辦事器信息 */
Properties props = new Properties();
props.put("mail.smtp.host", SMTP_MAIL_HOST);
props.put("mail.smtp.auth", "true");
/* 創立Session */
Session session = Session.getDefaultInstance(props, new SimpleAuthenticator(EMAIL_USERNAME, EMAIL_PASSWORD));
/* 發件人 */
Address[] senderArray = new Address[1];
senderArray[0] = new InternetAddress("[email protected]", "Nick Huang");
/* 郵件信息 */
MimeMessage message = new MimeMessage(session);
message.addFrom(senderArray);
message.addRecipient(Message.RecipientType.TO, new InternetAddress(TO_EMAIL_ADDRESS_1));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(CC_EMAIL_ADDRESS_1));
message.addRecipient(Message.RecipientType.CC, new InternetAddress(CC_EMAIL_ADDRESS_1));
message.addRecipient(Message.RecipientType.CC, new InternetAddress(TO_EMAIL_ADDRESS_1));
message.addRecipient(Message.RecipientType.BCC, new InternetAddress(BCC_EMAIL_ADDRESS_1));
message.setSubject("我是一封進修Java Mail的郵件");
message.setText("我是一封進修Java Mail的郵件的內容,請郵件過濾器高抬貴手。");
// 發送
Transport.send(message);
System.out.println("不是特殊不利,你可以去查收郵件了。");
}
} 

發送附件怎樣辦

認證器沿用,略。

發送附件demo:

package No003_發送附件怎樣辦;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
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 SendMailWithAttachment {
public static void main(String[] args) throws AddressException, MessagingException, UnsupportedEncodingException {
/* 必須的信息 */
String SMTP_MAIL_HOST = "smtp.163.com"; // 此郵件辦事器地址,自行去所屬郵件查詢
String EMAIL_USERNAME = "[email protected]";
String EMAIL_PASSWORD = "password";
String TO_EMAIL_ADDRESS_1 = "[email protected]";
/* 辦事器信息 */
Properties props = new Properties();
props.put("mail.smtp.host", SMTP_MAIL_HOST);
props.put("mail.smtp.auth", "true");
/* 創立Session */
Session session = Session.getDefaultInstance(props, new SimpleAuthenticator(EMAIL_USERNAME, EMAIL_PASSWORD));
/* 發件人 */
Address[] senderArray = new Address[1];
senderArray[0] = new InternetAddress(EMAIL_USERNAME);
/* 郵件信息 */
MimeMessage message = new MimeMessage(session);
message.addFrom(senderArray);
message.addRecipient(Message.RecipientType.TO, new InternetAddress(TO_EMAIL_ADDRESS_1));
message.setSubject("我是一封進修Java Mail的郵件");
BodyPart bodyPart = new MimeBodyPart();
bodyPart.setText("這是一封進修Java Mail的郵件的內容,請郵件過濾器高抬貴手。");
/* 附件 */
BodyPart attachmentPart1 = new MimeBodyPart();
DataSource source = new FileDataSource(new File("D:/文件壹.txt"));
attachmentPart1.setDataHandler(new DataHandler(source));
attachmentPart1.setFileName("=?GBK?B?" + new sun.misc.BASE64Encoder().encode("文件壹.txt".getBytes()) + "?=");
BodyPart attachmentPart2 = new MimeBodyPart();
source = new FileDataSource(new File("D:/文件貳.txt"));
attachmentPart2.setDataHandler(new DataHandler(source));
attachmentPart2.setFileName("=?GBK?B?" + new sun.misc.BASE64Encoder().encode("文件貳.txt".getBytes()) + "?=");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(bodyPart);
multipart.addBodyPart(attachmentPart1);
multipart.addBodyPart(attachmentPart2);
message.setContent(multipart);
// 發送
Transport.send(message);
System.out.println("不是特殊不利,你可以去查收郵件了。");
}
} 

還有,發送HTML郵件

認證器沿用,略。

其實就是告知收件客戶端用HTML解析襯著:

package No004_發送HTML郵件;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
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 HowToSendHTMLMail {
public static void main(String[] args) throws AddressException, MessagingException, UnsupportedEncodingException {
/* 必須的信息 */
String SMTP_MAIL_HOST = "smtp.163.com"; // 此郵件辦事器地址,自行去所屬郵件查詢
String EMAIL_USERNAME = "[email protected]";
String EMAIL_PASSWORD = "password";
String TO_EMAIL_ADDRESS_1 = "[email protected]";
/* 辦事器信息 */
Properties props = new Properties();
props.put("mail.smtp.host", SMTP_MAIL_HOST);
props.put("mail.smtp.auth", "true");
/* 創立Session */
Session session = Session.getDefaultInstance(props, new SimpleAuthenticator(EMAIL_USERNAME, EMAIL_PASSWORD));
/* 發件人 */
Address[] senderArray = new Address[1];
senderArray[0] = new InternetAddress(EMAIL_USERNAME);
/* 郵件信息 */
MimeMessage message = new MimeMessage(session);
message.addFrom(senderArray);
message.addRecipient(Message.RecipientType.TO, new InternetAddress(TO_EMAIL_ADDRESS_1));
message.setSubject("若何發送HTML的郵件");
/* 注釋 */
MimeBodyPart bodyPart = new MimeBodyPart();
bodyPart.setContent("<h1>loving you...</h2>", "text/html;charset=gb2312");
/* 封裝郵件各部門信息 */
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(bodyPart);
message.setContent(multipart);
// 發送
Transport.send(message);
System.out.println("不是特殊不利,你可以去查收郵件了。");
}
} 

要不,來個對象類?

認證器是必定的,沿用,略。

因為須要設置的屬性多且復雜,用個本身人簡略易用的屬生命名,所以來一個設置裝備擺設類

package No005_來一個對象類;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class MailSenderConfig {
private String SMTPMailHost; // 支撐SMTP協定的郵件辦事器地址
/* 用於登錄郵件辦事器 */
private String username;
private String password;
private String subject; // 題目
private String content; // 內容
private String fromMail; // 顯示從此郵箱收回郵件
private List<String> toMails; // 收件人
private List<String> ccMails; // 抄送人
private List<String> bccMails; // 機密抄送人
private List<File> attachments; // 附件
public MailSenderConfig(String sMTPMailHost, String subject,
String content, String fromMail) {
super();
SMTPMailHost = sMTPMailHost;
this.subject = subject;
this.content = content;
this.fromMail = fromMail;
}
public String getSMTPMailHost() {
return SMTPMailHost;
}
public void setSMTPMailHost(String sMTPMailHost) {
SMTPMailHost = sMTPMailHost;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFromMail() {
return fromMail;
}
public void setFromMail(String fromMail) {
this.fromMail = fromMail;
}
public List<String> getToMails() {
return toMails;
}
public void setToMails(List<String> toMails) {
this.toMails = toMails;
}
public List<String> getCcMails() {
return ccMails;
}
public void setCcMails(List<String> ccMails) {
this.ccMails = ccMails;
}
public List<String> getBccMails() {
return bccMails;
}
public void setBccMails(List<String> bccMails) {
this.bccMails = bccMails;
}
public List<File> getAttachments() {
return attachments;
}
public void setAttachments(List<File> attachments) {
this.attachments = attachments;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public void addToMail (String mail) {
if (this.toMails == null) {
this.toMails = new ArrayList<String>();
}
this.toMails.add(mail);
}
public void addCcMail (String mail) {
if (this.ccMails == null) {
this.ccMails = new ArrayList<String>();
}
this.ccMails.add(mail);
}
public void addBccMail (String mail) {
if (this.bccMails == null) {
this.bccMails = new ArrayList<String>();
}
this.bccMails.add(mail);
}
public void addAttachment (File f) {
if (this.attachments == null) {
this.attachments = new ArrayList<File>();
}
this.attachments.add(f);
}
} 

最初,就是對象類的部門,重要擔任幾個工作:依照Java Mail規矩作些初始化舉措、將自界說的屬性設置裝備擺設類翻譯並以Java Mail規矩設置、發送郵件。

還有,須要提下的是,由於對象類所供給的取代設置的屬性無限,更多的情形能夠不知足須要,所以裸露出MimeMessage,在不知足需求的情形開辟者可自行加工設置裝備擺設,而其他部門仍可沿用對象類。

package No005_來一個對象類;
import java.io.File;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
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 No002_各類發件人收件人抄送人怎樣辦.SimpleAuthenticator;
public class MailSender {
private MailSenderConfig c;
private MimeMessage message;
public MailSender(MailSenderConfig config) throws Exception {
super();
this.c = config;
this.setConfig();
}
/**
* 初始化
* @return
*/
private Session initSession() {
Properties props = new Properties();
if (c.getSMTPMailHost() != null && c.getSMTPMailHost().length() > 0) {
props.put("mail.smtp.host", c.getSMTPMailHost());
}
if (c.getUsername() != null && c.getUsername().length() > 0 && 
c.getPassword() != null && c.getPassword().length() > 0) {
props.put("mail.smtp.auth", "true");
return Session.getDefaultInstance(props, new SimpleAuthenticator(c.getUsername(), c.getPassword()));
} else {
props.put("mail.smtp.auth", "false");
return Session.getDefaultInstance(props);
}
}
/**
* 設置Java Mail屬性
* @throws Exception
*/
private void setConfig() throws Exception {
this.configValid();
Session s = this.initSession();
message = new MimeMessage(s);
/* 發件人 */
Address[] fromMailArray = new Address[1];
fromMailArray[0] = new InternetAddress(c.getFromMail());
message.addFrom(fromMailArray);
if (c.getToMails() != null && c.getToMails().size() > 0) {
for (String mail : c.getToMails()) {
message.addRecipient(Message.RecipientType.TO, new InternetAddress(mail));
}
}
if (c.getCcMails() != null && c.getCcMails().size() > 0) {
for (String mail : c.getCcMails()) {
message.addRecipient(Message.RecipientType.CC, new InternetAddress(mail));
}
}
if (c.getToMails() != null && c.getToMails().size() > 0) {
for (String mail : c.getToMails()) {
message.addRecipient(Message.RecipientType.BCC, new InternetAddress(mail));
}
}
// 郵件題目
message.setSubject(c.getSubject());
/* 注釋 */
MimeBodyPart bodyPart = new MimeBodyPart();
bodyPart.setContent(c.getContent(), "text/html;charset=gb2312");
/* 封裝郵件各部門信息 */
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(bodyPart);
message.setContent(multipart);
BodyPart attachmentPart = null;
DataSource ds = null;
if (c.getAttachments() != null && c.getAttachments().size() > 0) {
for (File f : c.getAttachments()) {
attachmentPart = new MimeBodyPart();
ds = new FileDataSource(f);
attachmentPart.setDataHandler(new DataHandler(ds));
attachmentPart.setFileName("=?GBK?B?" + new sun.misc.BASE64Encoder().encode(f.getName().getBytes()) + "?=");
multipart.addBodyPart(attachmentPart);
}
}
message.setContent(multipart);
}
/**
* 設置裝備擺設校驗
* @throws Exception
*/
private void configValid() throws Exception {
if (c == null) {
throw new Exception("設置裝備擺設對象為空");
}
if (c.getSMTPMailHost() == null || c.getSMTPMailHost().length() == 0) {
throw new Exception("SMTP辦事器為空");
}
if (c.getFromMail() == null && c.getFromMail().length() == 0) {
throw new Exception("發件人郵件為空");
}
if (c.getToMails() == null || c.getToMails().size() < 1) {
throw new Exception("收件人郵件為空");
}
if (c.getSubject() == null || c.getSubject().length() == 0) {
throw new Exception("郵件題目為空");
}
if (c.getContent() == null || c.getContent().length() == 0) {
throw new Exception("郵件內容為空");
}
}
/**
* 發送郵件
* @throws MessagingException
*/
public void send() throws MessagingException {
Transport.send(message);
}
/**
* 設置MimeMessage,裸露此對象以便於開辟者自行設置特性化的屬性
* @return
*/
public MimeMessage getMessage() {
return message;
}
/**
* 設置MimeMessage,裸露此對象以便於開辟者自行設置特性化的屬性
* @return
*/
public void setMessage(MimeMessage message) {
this.message = message;
}
} 
供給一個簡略的測試類
package No005_來一個對象類;
import java.io.File;
import javax.mail.internet.MimeMessage;
public class TestCall {
public static void main(String[] args) throws Exception {
/* 必須的信息 */
String SMTP_MAIL_HOST = "smtp.163.com"; // 此郵件辦事器地址,自行去所屬郵件查詢
String EMAIL_USERNAME = "[email protected]";
String EMAIL_PASSWORD = "password";
String TO_EMAIL_ADDRESS_1 = "[email protected]";
String TO_EMAIL_ADDRESS_2 = "[email protected]";
/* 應用情形一,正常應用 */
/*
MailSenderConfig c = new MailSenderConfig(SMTP_MAIL_HOST, 
"this is test mail for test java mail framework 3.", "this is content 3.", EMAIL_USERNAME);
c.setUsername(EMAIL_USERNAME);
c.setPassword(EMAIL_PASSWORD);
c.addToMail(TO_EMAIL_ADDRESS_1);
c.addToMail(TO_EMAIL_ADDRESS_2);
c.addCcMail(TO_EMAIL_ADDRESS_2);
c.addCcMail(TO_EMAIL_ADDRESS_1);
c.addAttachment(new File("d:/1.txt"));
MailSender ms = new MailSender(c);
ms.send();
System.out.println("sent...");
*/
/* 應用情形二,在更多情形下,對象類所作的設置其實不知足需求,故將MimeMessage裸露並 */
MailSenderConfig c = new MailSenderConfig(SMTP_MAIL_HOST, 
"this is test mail for test java mail framework 4.", "this is content 4.", EMAIL_USERNAME);
c.setUsername(EMAIL_USERNAME);
c.setPassword(EMAIL_PASSWORD);
c.addToMail(TO_EMAIL_ADDRESS_1);
c.addToMail(TO_EMAIL_ADDRESS_2);
c.addCcMail(TO_EMAIL_ADDRESS_2);
c.addCcMail(TO_EMAIL_ADDRESS_1);
c.addAttachment(new File("d:/1.txt"));
MailSender ms = new MailSender(c);
MimeMessage message = ms.getMessage();
message.setContent("this is the replaced content by MimeMessage 4.", "text/html;charset=utf-8");
ms.setMessage(message);
ms.send();
System.out.println("sent...");
}
} 

進級下對象類

在現實應用中,發明在批量發送郵件情形下,對象類的支撐欠好,好比發送100封郵件,依照上述對象類的邏輯,每發送一封郵件就樹立一個銜接,那末,100封不就100次了嗎?如許嚴重糟蹋啊。

因而,針對此點作些進級:

認證器是必定的,沿用,略。

設置裝備擺設類

import java.util.ArrayList;
import java.util.List;
public class MailSenderConfig {
private String SMTPMailHost; // 支撐SMTP協定的郵件辦事器地址
/* 用於登錄郵件辦事器 */
private String username;
private String password;
private String subject; // 題目
private String content; // 內容
private String fromMail; // 顯示從此郵箱收回郵件
private List<String> toMails; // 收件人
private List<String> ccMails; // 抄送人
private List<String> bccMails; // 機密抄送人
private List<Attachment> attachments; // 附件
private String contentType = "text/html;charset=utf-8";
/**
* 結構器
* @param sMTPMailHost SMTP辦事器
* @param subject 題目
* @param content 內容(默許以“text/html;charset=utf-8”情勢發送)
* @param fromMail 發送人地址
*/
public MailSenderConfig(String sMTPMailHost, String subject,
String content, String fromMail) {
super();
SMTPMailHost = sMTPMailHost;
this.subject = subject;
this.content = content;
this.fromMail = fromMail;
}
/**
* 結構器
* @param sMTPMailHost SMTP辦事器
* @param username 郵件辦事器用戶名
* @param password 郵件辦事器暗碼
* @param subject 題目
* @param content 內容(默許以“text/html;charset=utf-8”情勢發送)
* @param fromMail 發送人地址
*/
public MailSenderConfig(String sMTPMailHost, String username,
String password, String subject, String content, String fromMail) {
super();
SMTPMailHost = sMTPMailHost;
this.username = username;
this.password = password;
this.subject = subject;
this.content = content;
this.fromMail = fromMail;
}
public void addToMail (String mail) {
if (this.toMails == null) {
this.toMails = new ArrayList<String>();
}
this.toMails.add(mail);
}
public void addCcMail (String mail) {
if (this.ccMails == null) {
this.ccMails = new ArrayList<String>();
}
this.ccMails.add(mail);
}
public void addBccMail (String mail) {
if (this.bccMails == null) {
this.bccMails = new ArrayList<String>();
}
this.bccMails.add(mail);
}
public void addAttachment (Attachment a) {
if (this.attachments == null) {
this.attachments = new ArrayList<Attachment>();
}
this.attachments.add(a);
}
/*
* Getter and Setter
*/
public String getSMTPMailHost() {
return SMTPMailHost;
}
public void setSMTPMailHost(String sMTPMailHost) {
SMTPMailHost = sMTPMailHost;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFromMail() {
return fromMail;
}
public void setFromMail(String fromMail) {
this.fromMail = fromMail;
}
public List<String> getToMails() {
return toMails;
}
public void setToMails(List<String> toMails) {
this.toMails = toMails;
}
public List<String> getCcMails() {
return ccMails;
}
public void setCcMails(List<String> ccMails) {
this.ccMails = ccMails;
}
public List<String> getBccMails() {
return bccMails;
}
public void setBccMails(List<String> bccMails) {
this.bccMails = bccMails;
}
public List<Attachment> getAttachments() {
return attachments;
}
public void setAttachments(List<Attachment> attachments) {
this.attachments = attachments;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
} 
附件實體類
import java.io.File;
/**
* 郵件附件實體類
*/
public class Attachment {
private File file;
private String filename;
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public String getFilename() {
if (filename == null || filename.trim().length() == 0) {
return file.getName();
}
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public Attachment(File file, String filename) {
super();
this.file = file;
this.filename = filename;
}
public Attachment(File file) {
super();
this.file = file;
}
} 
籠統發送類
import java.util.Properties;
import javax.mail.Session;
public abstract class AbstractSessionMailSender {
protected Session session;
/**
* 初始化Session
* @return
*/
public static Session initSession(MailSenderConfig c) {
Properties props = new Properties();
if (c.getSMTPMailHost() != null && c.getSMTPMailHost().length() > 0) {
props.put("mail.smtp.host", c.getSMTPMailHost());
}
if (c.getUsername() != null && c.getUsername().length() > 0 && 
c.getPassword() != null && c.getPassword().length() > 0) {
props.put("mail.smtp.auth", "true");
return Session.getDefaultInstance(props, new SimpleAuthenticator(c.getUsername(), c.getPassword()));
} else {
props.put("mail.smtp.auth", "false");
return Session.getDefaultInstance(props);
}
}
/**
* 裸露Getter、Setter供給Session的可設置性,以支撐批量發送郵件/發送屢次郵件時,可緩存Session
* @return
*/
public Session getSession() {
return session;
}
public void setSession(Session session) {
this.session = session;
}
} 

發送類

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
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 MailSender extends AbstractSessionMailSender {
private MailSenderConfig c;
private MimeMessage message;
public MailSender(MailSenderConfig config) throws Exception {
super();
this.c = config;
this.setConfig();
}
public MailSender(MailSenderConfig config, Session session) throws Exception {
super();
this.c = config;
this.setConfig();
super.setSession(session);
}
/**
* 發送郵件
* @throws MessagingException
*/
public void send() throws MessagingException {
Transport.send(message);
}
/**
* 獲得MimeMessage,裸露此對象以便於開辟者自行設置特性化的屬性(此對象類不支撐的辦法可由開辟人員自行設置,設置終了設置回來)
* @return
*/
public MimeMessage getMessage() {
return message;
}
/**
* 設置MimeMessage,裸露此對象以便於開辟者自行設置特性化的屬性(此對象類不支撐的辦法可由開辟人員自行設置,設置終了設置回來)
* @return
*/
public void setMessage(MimeMessage message) {
this.message = message;
}
/**
* 設置Java Mail屬性
* @throws Exception
*/
private void setConfig() throws Exception {
this.configValid();
if (session == null) {
session = initSession(c);
}
message = new MimeMessage(session);
/* 發件人 */
Address[] fromMailArray = new Address[1];
fromMailArray[0] = new InternetAddress(c.getFromMail());
message.addFrom(fromMailArray);
if (c.getToMails() != null && c.getToMails().size() > 0) {
for (String mail : c.getToMails()) {
message.addRecipient(Message.RecipientType.TO, new InternetAddress(mail));
}
}
if (c.getCcMails() != null && c.getCcMails().size() > 0) {
for (String mail : c.getCcMails()) {
message.addRecipient(Message.RecipientType.CC, new InternetAddress(mail));
}
}
if (c.getToMails() != null && c.getToMails().size() > 0) {
for (String mail : c.getToMails()) {
message.addRecipient(Message.RecipientType.BCC, new InternetAddress(mail));
}
}
// 郵件題目
message.setSubject(c.getSubject());
/* 注釋 */
MimeBodyPart bodyPart = new MimeBodyPart();
bodyPart.setContent(c.getContent(), c.getContentType());
/* 封裝郵件各部門信息 */
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(bodyPart);
message.setContent(multipart);
/* 附件 */
BodyPart attachmentPart = null;
DataSource ds = null;
if (c.getAttachments() != null && c.getAttachments().size() > 0) {
for (Attachment a : c.getAttachments()) {
attachmentPart = new MimeBodyPart();
ds = new FileDataSource(a.getFile());
attachmentPart.setDataHandler(new DataHandler(ds));
attachmentPart.setFileName(MimeUtility.encodeText(a.getFilename()));
multipart.addBodyPart(attachmentPart);
}
}
message.setContent(multipart);
}
/**
* 設置裝備擺設校驗
* @throws Exception
*/
private void configValid() throws Exception {
if (c == null) {
throw new Exception("設置裝備擺設對象為空");
}
if (c.getSMTPMailHost() == null || c.getSMTPMailHost().length() == 0) {
throw new Exception("SMTP辦事器為空");
}
if (c.getFromMail() == null && c.getFromMail().length() == 0) {
throw new Exception("發件人郵件為空");
}
if (c.getToMails() == null || c.getToMails().size() < 1) {
throw new Exception("收件人郵件為空");
}
if (c.getSubject() == null || c.getSubject().length() == 0) {
throw new Exception("郵件題目為空");
}
if (c.getContent() == null || c.getContent().length() == 0) {
throw new Exception("郵件內容為空");
}
}
}
一個Junit的測試類
import java.io.File;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import org.junit.Test;
public class ReadMe {
/* 必須的信息 */
String SMTP_MAIL_HOST = "smtp.163.com"; // 此郵件辦事器地址,自行去所屬郵件辦事器描寫頁查詢
String EMAIL_USERNAME = "[email protected]";
String EMAIL_PASSWORD = "password";
String TO_EMAIL_ADDRESS_1 = "[email protected]";
/* 選填的信息 */
String TO_EMAIL_ADDRESS_2 = "[email protected]";
@Test
public void case1() throws Exception {
/* 應用情形一,正常應用 */
MailSenderConfig c = new MailSenderConfig(SMTP_MAIL_HOST, 
"this is a mail for test java mail framework in case1.", "this is content.", EMAIL_USERNAME);
c.setUsername(EMAIL_USERNAME);
c.setPassword(EMAIL_PASSWORD);
c.addToMail(TO_EMAIL_ADDRESS_1);
c.addToMail(TO_EMAIL_ADDRESS_2);
c.addCcMail(TO_EMAIL_ADDRESS_2);
c.addCcMail(TO_EMAIL_ADDRESS_1);
c.addAttachment(new Attachment(new File("d:/1.txt")));
MailSender ms = new MailSender(c);
ms.send();
System.out.println("sent...");
}
@Test
public void case2() throws Exception {
/* 應用情形二,在更多情形下,對象類所作的設置其實不知足需求,故將MimeMessage裸露以便於開辟者自行設置特性化的屬性 */
MailSenderConfig c = new MailSenderConfig(SMTP_MAIL_HOST, 
"this is a mail for test java mail framework in case2.", "this is content.", EMAIL_USERNAME);
c.setUsername(EMAIL_USERNAME);
c.setPassword(EMAIL_PASSWORD);
c.addToMail(TO_EMAIL_ADDRESS_1);
c.addToMail(TO_EMAIL_ADDRESS_2);
c.addCcMail(TO_EMAIL_ADDRESS_2);
c.addCcMail(TO_EMAIL_ADDRESS_1);
c.addAttachment(new Attachment(new File("d:/1.txt")));
MailSender ms = new MailSender(c);
MimeMessage message = ms.getMessage();
message.setContent("this is the replaced content by MimeMessage in case2.", "text/html;charset=utf-8");
ms.setMessage(message);
ms.send();
System.out.println("sent...");
}
@Test
public void case3() throws Exception {
/* 應用情形三,屢次發送郵件,可緩存Session,使屢次發送郵件均同享此Session,以削減反復創立Session
* 同時需留意緩存的Session的時效性
*/
MailSenderConfig c = new MailSenderConfig(SMTP_MAIL_HOST, 
"this is the first mail for test java mail framework to share session in case3.", "this is content.", EMAIL_USERNAME);
c.setUsername(EMAIL_USERNAME);
c.setPassword(EMAIL_PASSWORD);
c.addToMail(TO_EMAIL_ADDRESS_1);
c.addToMail(TO_EMAIL_ADDRESS_2);
c.addCcMail(TO_EMAIL_ADDRESS_2);
c.addCcMail(TO_EMAIL_ADDRESS_1);
c.addAttachment(new Attachment(new File("d:/1.txt")));
Session session = MailSender.initSession(c);
MailSender ms = new MailSender(c, session);
ms.send();
c.setSubject("this is the second mail for test java mail framework to share session in case3.");
c.setContent("this is content 2.");
ms = new MailSender(c, session);
ms.send();
System.out.println("sent...");
}
} 

總結

今朝,我碰到的需求就是這麼多,如往後碰見其他罕見的需求並有時光,會進一步添加。

以上所述是小編給年夜家引見的Java發送郵件碰到的罕見需求匯總的全體論述,願望對年夜家有所贊助,假如年夜家有任何疑問請給我留言,小編會實時答復年夜家的。在此也異常感激年夜家對網站的支撐!

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved