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

VB_*_*VB_ 3 java jakarta-mail

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

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

Rak*_*ith 11

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

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


adi*_*adi 6

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

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

例如:这里和这里