java sendemail_Java后端发送email实现

importjava.io.UnsupportedEncodingException;importjava.util.Date;importjava.util.Properties;importjavax.activation.DataHandler;importjavax.activation.FileDataSource;importjavax.mail.Address;importjavax.mail.BodyPart;importjavax.mail.Message;importjavax.mail.MessagingException;importjavax.mail.Multipart;importjavax.mail.NoSuchProviderException;importjavax.mail.Session;importjavax.mail.Transport;importjavax.mail.internet.AddressException;importjavax.mail.internet.InternetAddress;importjavax.mail.internet.MimeBodyPart;importjavax.mail.internet.MimeMessage;importjavax.mail.internet.MimeMultipart;importjavax.mail.internet.MimeUtility;/*** 邮件发送器

* @ClassName: SimpleMailSender

* @Description: TODO

*@authorOnlyMate

* @Date 2018年5月8日 下午6:23:20

**/

public classSimpleMailSender {/*** 以文本格式发送邮件

*

*@parammailInfo

* 待发送的邮件的信息*/

public booleansendTextMail(MailSenderInfo mailInfo) {//判断是否需要身份认证

MailAuthenticator authenticator = null;

Properties pro=mailInfo.getProperties();if(mailInfo.isValidate()) {//如果需要身份认证,则创建一个密码验证器

authenticator = newMailAuthenticator(mailInfo.getUserName(),

mailInfo.getPassword());

}//根据邮件会话属性和密码验证器构造一个发送邮件的session

Session sendMailSession =Session

.getDefaultInstance(pro, authenticator);try{//根据session创建一个邮件消息

Message mailMessage = newMimeMessage(sendMailSession);//创建邮件发送者地址

Address from = newInternetAddress(mailInfo.getFromAddress());//设置邮件消息的发送者

mailMessage.setFrom(from);//创建邮件的接收者地址,并设置到邮件消息中

if (mailInfo.getToAddress() != null

&& mailInfo.getToAddress().length() > 0) {

Address to= newInternetAddress(mailInfo.getToAddress());//Message.RecipientType.TO属性表示接收者的类型为TO

mailMessage.setRecipient(Message.RecipientType.TO, to);

}else if (mailInfo.getToBatchAddress() != null

&& mailInfo.getToBatchAddress().length > 0) {final int size =mailInfo.getToBatchAddress().length;

Address[] to= newAddress[size];for (int i = 0; i < size; i++) {

to[i]= newInternetAddress(mailInfo.getToBatchAddress()[i]);

}//Message.RecipientType.TO属性表示接收者的类型为TO

mailMessage.setRecipients(Message.RecipientType.TO, to);

}//设置邮件消息的主题

mailMessage.setSubject(mailInfo.getSubject());//设置邮件消息发送的时间

mailMessage.setSentDate(newDate());//设置邮件消息的主要内容

String mailContent =mailInfo.getContent();

mailMessage.setText(mailContent);//发送邮件

Transport.send(mailMessage);return true;

}catch(MessagingException ex) {

ex.printStackTrace();

}return false;

}/*** 以HTML格式发送邮件

*

*@parammailInfo

* 待发送的邮件信息*/

public booleansendHtmlMail(MailSenderInfo mailInfo) {//判断是否需要身份认证

MailAuthenticator authenticator = null;

Properties pro=mailInfo.getProperties();//如果需要身份认证,则创建一个密码验证器

if(mailInfo.isValidate()) {

authenticator= newMailAuthenticator(mailInfo.getUserName(),

mailInfo.getPassword());

}//根据邮件会话属性和密码验证器构造一个发送邮件的session

Session sendMailSession =Session

.getDefaultInstance(pro, authenticator);try{

sendMailSession.setDebug(true);//根据session创建一个邮件消息

Message mailMessage = newMimeMessage(sendMailSession);//创建邮件发送者地址

Address from = newInternetAddress(mailInfo.getFromAddress());//设置邮件消息的发送者

mailMessage.setFrom(from);//创建邮件的接收者地址,并设置到邮件消息中

if (mailInfo.getToAddress() != null

&& mailInfo.getToAddress().length() > 0) {

Address to= newInternetAddress(mailInfo.getToAddress());//Message.RecipientType.TO属性表示接收者的类型为TO

mailMessage.setRecipient(Message.RecipientType.TO, to);

}else if (mailInfo.getToBatchAddress() != null

&& mailInfo.getToBatchAddress().length > 0) {final int size =mailInfo.getToBatchAddress().length;

Address[] to= newAddress[size];for (int i = 0; i < size; i++) {

to[i]= newInternetAddress(mailInfo.getToBatchAddress()[i]);

}//Message.RecipientType.TO属性表示接收者的类型为TO

mailMessage.setRecipients(Message.RecipientType.TO, to);

}//设置邮件消息的主题

mailMessage.setSubject(mailInfo.getSubject());

mailMessage.setSubject(MimeUtility.encodeText(mailInfo.getSubject(),"UTF-8", "B"));//设置邮件消息发送的时间

mailMessage.setSentDate(newDate());//MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象

Multipart mainPart = newMimeMultipart();//-------------------------------beigin 文本---------------------//

//创建一个包含HTML内容的MimeBodyPart

BodyPart html = newMimeBodyPart();//设置HTML内容

html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");

mainPart.addBodyPart(html);//----------------------------------end 文本---------------------//

//-------------------------------beigin 附件---------------------// if(mailInfo.getAttachFileList() != null && mailInfo.getAttachFileList().size() > 0){for(String[] files : mailInfo.getAttachFileList()) {for(String file : files) {//邮件的附件

String fileName =file;if(fileName != null&&!fileName.trim().equals("")) {

MimeBodyPart mbp= newMimeBodyPart();

FileDataSource fileSource= newFileDataSource(fileName);

mbp.setDataHandler(newDataHandler(fileSource));try{

mbp.setFileName(MimeUtility.encodeText(fileSource.getName()));

}catch(UnsupportedEncodingException e) {

e.printStackTrace();

}

mainPart.addBodyPart(mbp);

}

}

}

}else{if(mailInfo.getAttachFileNames() != null && mailInfo.getAttachFileNames().length > 0){//邮件的附件

String fileName = mailInfo.getAttachFileNames()[0];if(fileName != null&&!fileName.trim().equals("")) {

MimeBodyPart mbp= newMimeBodyPart();

FileDataSource fileSource= newFileDataSource(fileName);

mbp.setDataHandler(newDataHandler(fileSource));try{

mbp.setFileName(MimeUtility.encodeText(fileSource.getName()));

}catch(UnsupportedEncodingException e) {

e.printStackTrace();

}

mainPart.addBodyPart(mbp);

}

}

}//----------------------------------end 附件---------------------//

//将MiniMultipart对象设置为邮件内容

mailMessage.setContent(mainPart);//发送邮件

Transport.send(mailMessage);

System.out.println("发送成功!");return true;

}catch(MessagingException ex) {

ex.printStackTrace();

}catch(UnsupportedEncodingException e1) {//TODO Auto-generated catch block

e1.printStackTrace();

}return false;

}/*** 以HTML格式发送多封邮件

*

*@parammailInfo

* 待发送的邮件信息*/

public booleansendBatchHtmlMail(MailSenderInfo mailInfo) {//判断是否需要身份认证

MailAuthenticator authenticator = null;

Properties pro=mailInfo.getProperties();

pro.setProperty("mail.transport.protocol", "smtp");//如果需要身份认证,则创建一个密码验证器

if(mailInfo.isValidate()) {

authenticator= newMailAuthenticator(mailInfo.getUserName(),

mailInfo.getPassword());

}//根据邮件会话属性和密码验证器构造一个发送邮件的session

Session sendMailSession =Session.getInstance(pro, authenticator);try{//发送邮件

sendMailSession.setDebug(true);

Transport transport=sendMailSession.getTransport();

transport.connect(mailInfo.getMailServerHost(),Integer.parseInt(mailInfo.getMailServerPort()),

mailInfo.getUserName(), mailInfo.getPassword());//创建邮件的接收者地址,并设置到邮件消息中

if (mailInfo.getToBatchAddress() != null

&& mailInfo.getToBatchAddress().length > 0) {final int size =mailInfo.getToBatchAddress().length;for (int i = 0; i < size; i++) {//根据session创建一个邮件消息

Message mailMessage = newMimeMessage(sendMailSession);//创建邮件发送者地址

Address from = newInternetAddress(mailInfo.getFromAddress());//设置邮件消息的发送者

mailMessage.setFrom(from);//设置邮件消息的主题

mailMessage.setSubject(mailInfo.getSubjects()[i]);

mailMessage.setSubject(MimeUtility.encodeText(mailInfo.getSubjects()[i],"UTF-8", "B"));//设置邮件消息发送的时间

mailMessage.setSentDate(newDate());//MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象

Multipart mainPart = newMimeMultipart();//-------------------------------beigin 文本---------------------//

//创建一个包含HTML内容的MimeBodyPart

BodyPart html = newMimeBodyPart();//设置HTML内容

html.setContent(mailInfo.getContents()[i], "text/html; charset=utf-8");

mainPart.addBodyPart(html);//----------------------------------end 文本---------------------//

//-------------------------------beigin 附件---------------------// if(mailInfo.getAttachFileList() != null && mailInfo.getAttachFileList().size() > 0){

String[] files=mailInfo.getAttachFileList().get(i);for(String file : files) {//邮件的附件

String fileName =file;if(fileName != null&&!fileName.trim().equals("")) {

MimeBodyPart mbp= newMimeBodyPart();

FileDataSource fileSource= newFileDataSource(fileName);

mbp.setDataHandler(newDataHandler(fileSource));try{

mbp.setFileName(MimeUtility.encodeText(fileSource.getName()));//System.out.println("ceshi2: " + MimeUtility.encodeText(fileSource.getName(),"utf-8",null));

} catch(UnsupportedEncodingException e) {

e.printStackTrace();

}

mainPart.addBodyPart(mbp);

}

}

}else{if(mailInfo.getAttachFileNames() != null && mailInfo.getAttachFileNames().length > 0){//邮件的附件

String fileName =mailInfo.getAttachFileNames()[i];if(fileName != null&&!fileName.trim().equals("")) {

MimeBodyPart mbp= newMimeBodyPart();

FileDataSource fileSource= newFileDataSource(fileName);

mbp.setDataHandler(newDataHandler(fileSource));try{

mbp.setFileName(MimeUtility.encodeText(fileSource.getName()));//System.out.println("ceshi: " + MimeUtility.encodeText(fileSource.getName(),"utf-8",null));

} catch(UnsupportedEncodingException e) {

e.printStackTrace();

}

mainPart.addBodyPart(mbp);

}

}

}//----------------------------------end 附件---------------------//

//将MiniMultipart对象设置为邮件内容

mailMessage.setContent(mainPart);

Address[] to= new Address[]{newInternetAddress(mailInfo.getToBatchAddress()[i])};

mailMessage.setRecipient(Message.RecipientType.TO, to[0]);

transport.sendMessage(mailMessage, to);

}

}

transport.close();

System.out.println("发送成功!");return true;

}catch(AddressException e) {

e.printStackTrace();

}catch(NoSuchProviderException e) {

e.printStackTrace();

}catch(MessagingException e) {

e.printStackTrace();

}catch(UnsupportedEncodingException e) {

e.printStackTrace();

}return false;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值