import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import com.pandabus.custom.dto.EmailInfo;
public class EmailUtils {
public static void sendEmail(EmailInfo email, String to) {
// 发件人电子邮箱
String from = "xxxx@sina.cn";
String smtp = "smtp.sina.cn";
// 获取系统属性
Properties properties = System.getProperties();
// 设置邮件服务器
properties.setProperty("mail.smtp.host", smtp);
properties.put("mail.smtp.auth", "true");
MyAuthenricator myauth = new MyAuthenricator();
// 获取默认session对象
Session session = Session.getDefaultInstance(properties, myauth);
try {
// 创建默认的 MimeMessage 对象
MimeMessage message = new MimeMessage(session);
// Set From: 头部头字段
message.setFrom(new InternetAddress(from));
// Set To: 头部头字段
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.addRecipient(Message.RecipientType.CC, new InternetAddress(from));
message.addRecipient(Message.RecipientType.CC, new InternetAddress("zou.yufei@pandabus.cn"));
// Set Subject: 头部头字段
message.setSubject(email.getTitle());
// 设置消息体
Multipart multipart = new MimeMultipart();
BodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(email.getContent(), "text/html;charset=utf-8");
multipart.addBodyPart(htmlPart);
message.setContent(multipart);
// 发送消息
Transport.send(message);
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
static class MyAuthenricator extends Authenticator {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("xxx@sina.cn", "xxx);
}
}
}
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
public class EmailInfo {
private String title;
private List<String> content = new ArrayList<>();
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return StringUtils.join(content, "<br/>");
}
public void addContent(String line) {
this.content.add(line);
}
}
static void sendEmail(String title, String request, String response) {
EmailInfo email = new EmailInfo();
email.setTitle(title);
email.addContent("request:" + request);
email.addContent("response:" + response);
EmailUtils.sendEmail(email, "xxx@pandabus.cn");
}
网友评论