Java Mail API:通过企业outlook acount发送电子邮件

我希望我的程序能够从我的企业Outlook帐户发送电子邮件。 我看了很多JMA的例子,似乎不是我想要的。

  1. 我在哪里可以找到通过outlook发送邮件的简单示例?
  2. 我应该将邮件系统移动到单独的服务应用程序吗? 如果是这样,为什么?

您所需要的只是公司帐户的SMTP设置。 使用Java mail API在程序中设置它们就可以了。 例如

Properties props = System.getProperties(); props.put("mail.smtp.host", "your server here"); Session session = Session.getDefaultInstance(props, null); 

例如: 这里和这里

您需要先下载javax.mail JAR。 然后尝试以下代码:

 import java.io.IOException; import java.util.Properties; 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; public class SendMail { public static void main(String[]args) throws IOException { final String username = "enter your username"; final String password = "enter your password"; Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", "outlook.office365.com"); props.put("mail.smtp.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("enter your outlook mail address")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("Enter the recipient mail address")); message.setSubject("Test"); message.setText("HI"); Transport.send(message); System.out.println("Done"); } catch (MessagingException e) { throw new RuntimeException(e); } } } 

从我所看到的,您缺少以下导入:

 import java.io.IOException; 

只需将它包含在此类开头的类导入中,您的问题就应该解决了。

我尝试使用outlook.office365.com作为主机名,并获得authentication unaccepted exception 。 在尝试使用smtp-mail.outlook.com我可以使用Javamail API通过outlook发送邮件。

有关详细信息, 请查看Outlook官方网站上的Outlook设置 。

完整的工作演示代码阅读此答案 。