企业邮箱发送邮件
package com.ys.utils;
import com.sun.mail.util.MailSSLSocketFactory;
import com.ys.config.MailConfig;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.util.Date;
import java.util.Properties;
public class MailUtils {
public static void sendEmail(String toMail, String subject, String messages){
Properties prop = new Properties();
//协议
prop.setProperty("mail.transport.protocol", "smtp");
//服务器
prop.setProperty("mail.smtp.host", "smtp.exmail.qq.com");
//端口
prop.setProperty("mail.smtp.port", "465");
//使用smtp身份验证
prop.setProperty("mail.smtp.auth", "true");
//使用SSL,企业邮箱必需!
//开启安全协议
MailSSLSocketFactory sf = null;
try {
sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
} catch (GeneralSecurityException e1) {
e1.printStackTrace();
}
prop.put("mail.smtp.ssl.enable", "true");
prop.put("mail.smtp.ssl.socketFactory", sf);
//
//获取Session对象
Session s = Session.getDefaultInstance(prop,new Authenticator() {
//此访求返回用户和密码的对象
@Override
protected PasswordAuthentication getPasswordAuthentication() {
//邮箱账号,密码
PasswordAuthentication pa = new PasswordAuthentication(MailConfig.FROM_MAIL, MailConfig.MAIL_PASSWPRD);
return pa;
}
});
//设置session的调试模式,发布时取消
s.setDebug(true);
MimeMessage mimeMessage = new MimeMessage(s);
try {
//发件人邮箱,显示的发件人(可以是任何内容)
mimeMessage.setFrom(new InternetAddress(MailConfig.FROM_MAIL,MailConfig.subject));
//收件人
mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(toMail));
//设置主题
mimeMessage.setSubject(subject);
mimeMessage.setSentDate(new Date());
//设置内容
mimeMessage.setText(messages);
mimeMessage.saveChanges();
//发送
Transport.send(mimeMessage);
} catch (MessagingException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e){
e.getCause();
}
}
}
注意:需开启IMAP/SMTP服务或POP/SMTP服务