欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java发送邮件遇到的常见需求汇总

程序员文章站 2024-03-12 13:48:14
基于smtp发送一个简单的邮件 首先,需要一个认证器: package no001_基于smtp的文本邮件; import javax.mail.authen...

基于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 = "example_email@163.com";
string email_password = "mypassword";
string to_email_address = "example_email_too@qq.com";
/* 服务器信息 */
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 = "example@163.com";
string email_password = "mypassword";
string to_email_address_1 = "example@163.com";
string cc_email_address_1 = "example@163.com";
string bcc_email_address_1 = "example@163.com";
/* 服务器信息 */
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("example@163.com", "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 = "example@163.com";
string email_password = "password";
string to_email_address_1 = "example@163.com";
/* 服务器信息 */
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 = "example@163.com";
string email_password = "password";
string to_email_address_1 = "example@163.com";
/* 服务器信息 */
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 = "example@163.com";
string email_password = "password";
string to_email_address_1 = "example@163.com";
string to_email_address_2 = "example@163.com";
/* 使用情况一,正常使用 */
/*
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 = "example@163.com";
string email_password = "password";
string to_email_address_1 = "example@163.com";
/* 选填的信息 */
string to_email_address_2 = "example@163.com";
@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发送邮件遇到的常见需求汇总的全部叙述,希望对大家有所帮助