使用Javamail发送邮件Util

maven:
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>${javax-mail.version}</version>
</dependency>
<dependency>

config.properties:
######发送邮件配置##########
mail.smtp.host =
mail.smtp.port=465
mail.smtp.protocol=smtp
#######发送方账号和密码
mail.sender.username=
mail.sender.password=
#######收件人邮箱,多人以逗号(英文)隔开
mail.receive.user=
code:
package com.exl.analysis.core.util;

import com.exl.framework.common.util.PropertyUtils;
import com.exl.framework.log.CustomLogger;
import com.sun.mail.util.MailSSLSocketFactory;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.security.GeneralSecurityException;
import java.util.List;
import java.util.Properties;

public class SendEmailUtil {

private MimeMessage message;

private String mailHost = "";
private String mailPort = "";
private String mailProtocol = "";
private String sender_username = "";
private String sender_password = "";
// 收件人列表,以","分割

private Properties properties = new Properties();

/*
* 初始化方法
*/
public SendEmailUtil(Boolean debug) {
this.mailHost = PropertyUtils.get("mail.smtp.host");
this.mailPort = PropertyUtils.get("mail.smtp.port");
this.mailProtocol = PropertyUtils.get("mail.smtp.protocol");
this.sender_username = PropertyUtils .get("mail.sender.username");
this.sender_password = PropertyUtils.get("mail.sender.password");
}

/**
* 指定发送邮件
*
* @param subject
* 邮件主题
* @param sendHtml
* 邮件内容
* @param filePath
* 附件列表
* @param receiveUser
* 收件人(多个以英文逗号隔开)
*/
public boolean sendEmail(String subject,String sendHtml,List<String> filePath,String receiveUser){
Properties prop = new Properties();
// 协议
prop.setProperty("mail.transport.protocol", mailProtocol);
// 服务器
prop.setProperty("mail.smtp.host", mailHost);
// 端口
prop.setProperty("mail.smtp.port", mailPort);
// 使用smtp身份验证
prop.setProperty("mail.smtp.auth", "true");
// 使用SSL,企业邮箱必需!
// 开启安全协议
MailSSLSocketFactory sf = null;
try {
sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
} catch (GeneralSecurityException e1) {
System.out.println("开启SSL加密异常!");
e1.printStackTrace();
return false;
}
prop.put("mail.smtp.ssl.enable", "true");
prop.put("mail.smtp.ssl.socketFactory", sf);
Session session = Session.getDefaultInstance(prop, new MyAuthenticator(
sender_username, sender_password));
// 开启DEBUG模式,在控制台中或日志中有日志信息显示,也就是可以从控制台中看一下服务器的响应信息;
session.setDebug(true);
message = new MimeMessage(session);
try{
message.setFrom(new InternetAddress(sender_username));
//邮件主题
message.setSubject(subject);
// 向multipart对象中添加邮件的各个部分内容,包括文本内容和附件
Multipart multipart = new MimeMultipart();
// 添加邮件正文
BodyPart contentPart = new MimeBodyPart();
contentPart.setContent(sendHtml, "text/html;charset=UTF-8");
multipart.addBodyPart(contentPart);
if (filePath != null && filePath.size() > 0) {
for (String filename : filePath) {
BodyPart attachmentBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(filename);
attachmentBodyPart.setDataHandler(new DataHandler(
source));
// MimeUtility.encodeWord可以避免文件名乱码
attachmentBodyPart.setFileName(MimeUtility
.encodeWord(source.getName()));
multipart.addBodyPart(attachmentBodyPart);
}
// 移走集合中的所有元素
filePath.clear();
}
// 将multipart对象放到message中

message.setContent(multipart);
message.setRecipients(Message.RecipientType.TO,receiveUser);
message.saveChanges();
// 发送
Transport.send(message);
System.out.println("send success!");
return true;
}catch (Exception e){
return false;
}
}



}

转载于:https://www.cnblogs.com/zhangqian1031/p/8423890.html

/* * 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、付费专栏及课程。

余额充值