我很好奇有没有办法直接从 Java 代码发送带有附件的电子邮件。该电子邮件属于公司mylogin
@companyxxx.com` 即使用Java 操作Outlook?或者也许我不需要操作Outlook,有登录名和密码等人员就足够了……
问问题
2981 次
1 回答
2
是的,你可以使用javamail做到这一点,你可以从这里下载 jar 。对于 Outlook,您只需按如下方式设置属性:
Properties props = new Properties();
props.put("mail.smtp.user", username);
props.put("mail.smtp.host", "smtp.live.com");
props.put("mail.smtp.port", "25");
props.put("mail.debug", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.EnableSSL.enable", "true");
props.setProperty("mail.smtp.port", "587");
props.setProperty("mail.smtp.socketFactory.port", "587");
或者,如果您想要完整的示例,请使用以下方法:
public int sendMailWithAttachment(String to, String subject, String body, String filepath, String sendFileName) {
final String username = "YOUR EMAIL";
final String password = "YOUR PWD";
Properties props = new Properties();
props.put("mail.smtp.user", username);
props.put("mail.smtp.host", "smtp.live.com");
props.put("mail.smtp.port", "25");
props.put("mail.debug", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.EnableSSL.enable", "true");
props.setProperty("mail.smtp.port", "587");
props.setProperty("mail.smtp.socketFactory.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
message.setSubject(subject);
message.setText(body);
BodyPart messageBodyPart = new MimeBodyPart();
Multipart multipart = new MimeMultipart();
BodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent("<html><body>HELLO</body></html>", "text/html");
DataSource source = new FileDataSource(filepath);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(sendFileName);
multipart.addBodyPart(messageBodyPart);
multipart.addBodyPart(htmlPart);
message.setContent(multipart);
Transport.send(message);
return 1;
} catch (Exception e) {
return 0;
}
}
于 2013-10-11T06:16:35.347 回答