Java Mail API:通过企业Outlook帐户发送电子邮件

时间:2013-12-16 14:42:29

标签: java javamail

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

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

4 个答案:

答案 0 :(得分:10)

您需要先下载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);
        }
    }
}

答案 1 :(得分:6)

您所需要的只是公司帐户的SMTP设置。使用Java mail API在程序中设置它们就是这样。 e.g。

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

示例:herehere

答案 2 :(得分:1)

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

import java.io.IOException;

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

答案 3 :(得分:1)

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

有关展望官方网站的更多详情Check out the settings of Outlook

完整的工作演示代码Read this answer

相关问题