之前写过一篇发送邮件到邮箱的,但是只支持文本发送,这篇文章将支持附件+文本内容 发送
try {
Properties props = new Properties();
// 开启debug调试
props.setProperty("mail.debug", "true");
// 发送服务器需要身份验证
props.setProperty("mail.smtp.auth", "true");
// 设置邮件服务器主机名
props.setProperty("mail.host", "smtp.qq.com");
// 发送邮件协议名称
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("远控服务端错误");
//消息
String errorLog = String.valueOf(AppVolley.getParamsObject()) +
"\n" +
errorMsg +
"\n";
try {
MimeBodyPart minMimeBodyPart = new MimeBodyPart();
//混合的组合关系
MimeMultipart msgMultipart = new MimeMultipart();
// ----------- 发送文本内容
MimeBodyPart mbpContent = new MimeBodyPart();
mbpContent.setText(errorLog);
msgMultipart.addBodyPart(mbpContent);
// -----------发送附件
//得到日志源
DataSource logData = new FileDataSource(FileUtil.getLogPath());
//数据处理器
DataHandler logHandler = new DataHandler(logData);
minMimeBodyPart.setDataHandler(logHandler);
//处理附件名称中文(附带文件路径)乱码问题
minMimeBodyPart.setFileName(MimeUtility.encodeText("服务端日志log"));
//添加附件到消息中
msgMultipart.addBodyPart(minMimeBodyPart);
msg.setContent(msgMultipart);
} catch (Exception e) {
e.printStackTrace();
}
msg.setFrom(new InternetAddress("发送方@qq.com"));
Transport transport = session.getTransport();
transport.addTransportListener(new TransportListener() {
@Override public void messageDelivered(TransportEvent e) {
//发送后清掉
}
@Override public void messageNotDelivered(TransportEvent e) {
}
@Override public void messagePartiallyDelivered(TransportEvent e) {
}
});
transport.connect("smtp.qq.com", "发送方@qq.com", "发送方密码");//发送方密码为POP3/SMTP服务码
transport.sendMessage(msg, new Address[]{new InternetAddress("接收方@qq.com")});
transport.close();
} catch (Exception e) {
e.printStackTrace();
}
}
网友评论