目前研究一下使用Java发送带有附件的邮件,从网上搜索了一下发现都存在各种各样的问题。在这里总结一下,展示一下基础代码,防止遗忘。
代码
public static boolean sendMailpublic static boolean sendMail(String subject, String toMail,
String content, String... files) {
boolean isFlag = false;
try {
String smtpFromMail = "你的QQ号码@qq.com"; // 账号
String pwd = "QQ上面申请的授权码"; // 密码
int port = 465; // 端口
String host = "smtp.qq.com"; // 端口
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.setProperty("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props);
session.setDebug(false);
MimeMessage message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(smtpFromMail, "QQ邮件测试"));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(toMail));
message.setSubject(subject);
message.addHeader("charset", "UTF-8");
/* 添加正文内容 */
Multipart multipart = new MimeMultipart();
BodyPart contentPart = new MimeBodyPart();
contentPart.setText(content);
contentPart.setHeader("Content-Type",
"text/html; charset=UTF-8");
multipart.addBodyPart(contentPart);
/* 添加附件 */
for (String file : files) {
File usFile = new File(file);
MimeBodyPart fileBody = new MimeBodyPart();
DataSource source = new FileDataSource(file);
fileBody.setDataHandler(new DataHandler(source));
sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
fileBody.setFileName("=?GBK?B?"
+ enc.encode(usFile.getName().getBytes()) + "?=");
multipart.addBodyPart(fileBody);
}
message.setContent(multipart);
message.setSentDate(new Date());
message.saveChanges();
Transport transport = session.getTransport("smtp");
transport.connect(host, port, smtpFromMail, pwd);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
isFlag = true;
} catch (Exception e) {
isFlag = false;
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
return isFlag;
}
public static void main(String[] args) {
boolean res = Main.sendMail("这是一封测试邮件", "想要发送的邮件地址",
"朋友好久不见", "附件路径");
System.out.println("Resuylt: " + res);
}
注
- 使用Java客户端配置QQ邮箱发送邮件,需要现在QQ邮箱网页上申请授权码,发送邮件时放在密码的位置;
- 特别需要注意发送邮件的标题、正文内容的编码格式问题,不然容易造成乱码现象。
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!