[英]How to send private companies' emails with attchments directly from Java code?
我很好奇,有没有办法直接从Java代码发送带有附件的电子邮件。 该电子邮件属于mylogin
@ companyxxx.com公司。即使用Java操作Outlook? 也许我不需要操纵Outlook,而拥有登录名,密码和其他人员就足够了...
是的,您可以使用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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.