java 邮件 工具类_java邮件工具类【最终版】

这是一个Java编写的邮件发送工具类,支持文本和HTML格式的邮件。类中包含`sendTextMail`和`sendHtmlMail`两个方法,分别用于发送纯文本和HTML格式的邮件。邮件发送涉及的身份验证、邮件头信息设置(包括发件人、收件人、抄送人、密送人、主题等)、内容设置以及附件处理等功能。
摘要由CSDN通过智能技术生成

packagecommon;/*** Created by zipon on 2017/4/21.*/

importjava.io.File;importjava.io.UnsupportedEncodingException;importjava.security.GeneralSecurityException;importjava.util.ArrayList;importjava.util.Date;importjava.util.Properties;importjavax.activation.DataHandler;importjavax.activation.FileDataSource;importjavax.mail.Address;importjavax.mail.Message;importjavax.mail.MessagingException;importjavax.mail.Multipart;importjavax.mail.Session;importjavax.mail.Transport;importjavax.mail.internet.InternetAddress;importjavax.mail.internet.MimeBodyPart;importjavax.mail.internet.MimeMessage;importjavax.mail.internet.MimeMultipart;/*** 邮件发送

*@authorxdemo.org

**/

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

*

*@parammail

* 待发送的邮件的信息

*@throwsGeneralSecurityException*/

public boolean sendTextMail(Email mail) throwsGeneralSecurityException {//判断是否需要身份认证

MailAuthenticator authenticator = null;

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

authenticator = newMailAuthenticator(mail.getUserName(), mail.getPassword());

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

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

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

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

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

Address to = newInternetAddress(mail.getToAddress());

mailMessage.setRecipients(Message.RecipientType.TO, to);//创建邮件抄送者地址

if(mail.getCCAddress()!=null) {//Address cc = new InternetAddress(mail.getCCAddress());

mailMessage.setRecipients(Message.RecipientType.CC, InternetAddress.parse(mail.getCCAddress()));

}//创建邮件暗抄送者地址

if(mail.getBCCAddress()!=null) {//Address bcc = new InternetAddress(mail.getBCCAddress());

mailMessage.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(mail.getBCCAddress()));

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

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

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

String mailContent =mail.getContent();

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

Transport.send(mailMessage);return true;

}catch(MessagingException ex) {

ex.printStackTrace();

}return false;

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

*

*@parammail

* 待发送的邮件信息

*@throwsGeneralSecurityException

*@throwsUnsupportedEncodingException*/

public boolean sendHtmlMail(Email mail) throwsGeneralSecurityException, UnsupportedEncodingException {//判断是否需要身份认证

MailAuthenticator authenticator = null;

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

if(mail.isValidate()) {

authenticator= newMailAuthenticator(mail.getUserName(), mail.getPassword());

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

Session sendMailSession =Session.getDefaultInstance(props, authenticator);

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

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

Address from = new InternetAddress(mail.getFromAddress(),mail.getFromNickName()==null?"":mail.getFromNickName());//设置邮件消息的发送者

mailMessage.setFrom(from);//创建邮件的接收者地址,并设置到邮件消息中,可以设置多个收件人,逗号隔开//Message.RecipientType.TO属性表示接收者的类型为TO,CC表示抄送,BCC暗送

mailMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(mail.getToAddress()));//创建邮件抄送者地址

if(mail.getCCAddress()!=null) {//Address cc = new InternetAddress(mail.getCCAddress());

mailMessage.setRecipients(Message.RecipientType.CC, InternetAddress.parse(mail.getCCAddress()));

}//创建邮件暗抄送者地址s

if(mail.getBCCAddress()!=null) {//Address bcc = new InternetAddress(mail.getBCCAddress());

mailMessage.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(mail.getBCCAddress()));

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

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

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

Multipart mainPart = newMimeMultipart();//创建一个包含HTML内容的MimeBodyPart

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

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

mainPart.addBodyPart(html);//设置信件的附件(用本地上的文件作为附件)

FileDataSource fds=null;

DataHandler dh=null;if (mail.getAttachments()!=null) {for(File file : mail.getAttachments()) {

html= newMimeBodyPart();

fds= newFileDataSource(file);

dh= newDataHandler(fds);

html.setFileName(file.getName());

html.setDataHandler(dh);

mainPart.addBodyPart(html);

}

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

mailMessage.setContent(mainPart);

mailMessage.saveChanges();//发送邮件

Transport.send(mailMessage);return true;

}catch(MessagingException ex) {

ex.printStackTrace();

}return false;

}public static void main(String[] args) throwsGeneralSecurityException, UnsupportedEncodingException {//final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";//Properties props = System.getProperties();//props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);//

//props.setProperty("mail.smtp.socketFactory.fallback", "false");//props.setProperty("mail.smtp.socketFactory.port", "465");//这个类主要是设置邮件

Email mailInfo = newEmail();

mailInfo.setCCAddress("xxxx@qq.com");

mailInfo.setMailServerHost("smtp.163.com");

mailInfo.setMailServerPort("25");

mailInfo.setValidate(true);

mailInfo.setFromNickName("xxx");

mailInfo.setUserName("xxx@163.com"); //实际发送者

mailInfo.setPassword("xxx");//您的邮箱密码/授权码

mailInfo.setFromAddress("xxx@163.com"); //设置发送人邮箱地址

mailInfo.setToAddress("xxx@qq.com,xxx@qq.com"); //设置接受者邮箱地址

mailInfo.setSubject("【镁锭项目计划回归】按照这次的来。反馈");

mailInfo.setContent("已完成!反馈。这次一定行!

第一行第一列第二行第二列
");//mailInfo.setAttachments(new ArrayList(){//{//add(new File("D:\\driver\\geckodriver.exe"));//add(new File("D:\\driver\\chromedriver.exe"));//}//});//这个类主要来发送邮件

MailSender sms = newMailSender();//sms.sendTextMail(mailInfo);//发送文体格式

sms.sendHtmlMail(mailInfo); //发送html格式,需要发送附件或者html(一般是table可用,链接好像不行)时,选择这个

}

}

/* * JCatalog Project */ package com.hexiang.utils; import java.util.List; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.Properties; import javax.mail.Session; import javax.mail.Transport; import javax.mail.Message; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.hexiang.exception.CatalogException; /** * Utility class to send email. * * @author <a href="380595305@qq.com">hexiang</a> */ public class EmailUtil { //the logger for this class private static Log logger = LogFactory.getLog("com.hexiang.util.EmailUtil"); /** * Send email to a single recipient. * * @param smtpHost the SMTP email server address * @param senderAddress the sender email address * @param senderName the sender name * @param receiverAddress the recipient email address * @param sub the subject of the email * @param msg the message content of the email */ public static void sendEmail(String smtpHost, String senderAddress, String senderName, String receiverAddress, String sub, String msg) throws CatalogException { List<String> recipients = new ArrayList<String>(); recipients.add(receiverAddress); sendEmail(smtpHost, senderAddress, senderName, recipients, sub, msg); } /** * Send email to a list of recipients. * * @param smtpHost the SMTP email server address * @param senderAddress the sender email address * @param senderName the sender name * @param recipients a list of receipients email addresses * @param sub the subject of the email * @param msg the message content of the email */ public static void sendEmail(String smtpHost, String senderAddress, String senderName, List<String> recipients, String sub, String msg) throws CatalogException { if (smtpHost == null) { String errMsg = "Could not send email: smtp host address is null"; logger.error(errMsg); throw new CatalogException(errMsg); } try { Properties props = System.getProperties(); props.put("mail.smtp.host", smtpHost); Session session = Session.getDefaultInstance(props, null ); MimeMessage message = new MimeMessage( session ); message.addHeader("Content-type", "text/plain"); message.setSubject(sub); message.setFrom(new InternetAddress(senderAddress, senderName)); for (Iterator<String> it = recipients.iterator(); it.hasNext();) { String email = (String)it.next(); message.addRecipients(Message.RecipientType.TO, email); } message.setText(msg); message.setSentDate( new Date() ); Transport.send(message); } catch (Exception e) { String errorMsg = "Could not send email"; logger.error(errorMsg, e); throw new CatalogException("errorMsg", e); } } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值