实现发邮件功能
1、配置邮件服务器主机名:private static String myEmailSMTPHost = “smtp.qq.com”;(邮箱服务器前面加“smtp.”)
2、配置private static String myEmailAccount = “123456789@qq.com”;(在配置的邮箱服务器上创建邮箱)
3、开启SMTP服务,配置授权码:发件人邮箱密码(授权码)
private static String myEmailPassword = “gebkgxzpspvhbejc”;
4、创建邮件工具类
package com.tanwuapp.common.utils;
import com.sun.mail.util.MailSSLSocketFactory;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Properties;
public class EmailUtil {
private static String myEmailSMTPHost = "smtp.exmail.qq.com";
private static String myEmailAccount = "wanlin@zuzuya.cn";
private static String myEmailPassword = "PVTDcqRFk6hZP93Y";
public static void sendEmail(String toEmailAddress, String emailTitle, String emailContent) {
Transport transport=null;
try {
Properties props = new Properties();
props.setProperty("mail.smtp.auth", "true");
props.put("mail.smtp.port", 465);
props.setProperty("mail.smtp.host", myEmailSMTPHost);
props.setProperty("mail.transport.protocol", "smtp");
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.ssl.socketFactory", sf);
Session session = Session.getInstance(props);
Message msg = new MimeMessage(session);
msg.setSubject(emailTitle);
msg.setSentDate(new Date());
msg.setText(emailContent);
msg.setFrom(new InternetAddress(myEmailAccount,"租租鸭 info", "UTF-8"));
transport = session.getTransport();
transport.connect( myEmailSMTPHost, myEmailAccount, myEmailPassword);
transport.sendMessage(msg, new Address[] { new InternetAddress(toEmailAddress) });
}catch (Exception e){
LogUtils.system.error(e);
}finally {
if(transport!=null){
try {
transport.close();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
}
}
5、调用邮件工具类发邮件
StringBuilder emailStr = new StringBuilder("订单号:" + "123456789");
emailStr.append("\n姓名:" + "租租鸭");
emailStr.append("\n 第" + "1"+ "期");
emailStr.append("\n 已扣款成功");
EmailUtil.sendEmail("123456789@qq.com", "坏帐扣款成功通知", emailStr.toString());
|