mvn依赖:
<dependency>
<groupId>mail</groupId>
<artifactId>mail</artifactId>
<version>1.0.1</version>
</dependency>
<dependency>
<groupId>activation</groupId>
<artifactId>activation</artifactId>
<version>1.2</version>
</dependency>
package cn.sumpay.xj.crowdsourcing.util;
import cn.sumpay.xj.crowdsourcing.model.CsTargetPayeeInfo;
import cn.sumpay.xj.crowdsourcing.model.CsTask;
import com.sun.mail.util.MailSSLSocketFactory;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.math.BigDecimal;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
public class SendEmail {
public static void main(String[] args) {
try {
sendMail("你好 hello", "smtp.163.com", "xxxxx@163.com", "xxxx.sp@fosun.com","xxxxZYYHTEEDP", "xxxxxx用户");
} catch (MessagingException e) {
e.printStackTrace();
} catch (GeneralSecurityException e) {
e.printStackTrace();
}
}
/**
*
* @param content 发送内容
* @param emailSmtp 发送的邮件服务器
* @param fromMail 发送方邮箱
* @param toEmail 接收方邮箱
* @param authCode 发送方邮箱授权码 【邮箱密码】
* @param title 发送的邮件标题
* @throws MessagingException
* @throws GeneralSecurityException
*/
public static void sendMail(String content, String emailSmtp, String fromMail, String toEmail, String authCode, String title) throws MessagingException, GeneralSecurityException {
//创建一个配置文件并保存
Properties properties = new Properties();
properties.setProperty("mail.host", emailSmtp);
properties.setProperty("mail.transport.protocol","smtp");
properties.setProperty("mail.smtp.auth","true");
//QQ存在一个特性设置SSL加密
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
properties.put("mail.smtp.ssl.enable", "true");
properties.put("mail.smtp.ssl.socketFactory", sf);
//创建一个session对象
Session session = Session.getDefaultInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication( fromMail,authCode);
}
});
//开启debug模式
session.setDebug(true);
//获取连接对象
Transport transport = session.getTransport();
//连接服务器
transport.connect( emailSmtp, fromMail,authCode );
//创建邮件对象
MimeMessage mimeMessage = new MimeMessage(session);
//邮件发送人
mimeMessage.setFrom(new InternetAddress( fromMail ));
//邮件接收人
mimeMessage.setRecipient(Message.RecipientType.TO,new InternetAddress(toEmail));
//邮件标题
mimeMessage.setSubject(title);
//邮件内容
mimeMessage.setContent( content,"text/html;charset=UTF-8");
//发送邮件
transport.sendMessage(mimeMessage,mimeMessage.getAllRecipients());
//关闭连接
transport.close();
}
}