通过适用于Office 365的Java API发送邮件

pw136qt2  于 2023-02-20  发布在  Java
关注(0)|答案(2)|浏览(289)

您好,我目前正在开发Java应用程序,将通过Java邮件API(1.6.2)发送邮件给多个收件人,我已经按照微软文档配置了SMTP问题是代码与我的个人Hotmail电子邮件ID,但它失败的企业办公室365帐户。
错误:javax.mail。验证失败异常:535 5.7.3验证不成功[产品编号1PR0101CA0066.INDPRD01.PROD.OUTLOOK.COM]
POP和IMAP正在工作(接收邮件),我可以在Office 365 Web中使用密码登录,我也试过更改密码。
代码:

User user = Credentials.ACC;
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.office365.com");//outlook.office365.com
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "587");//25
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.transport.protocol", "smtp");
//props.put("mail.smtp.ssl.enable", true);

Session session = Session.getInstance(props, new Authenticator() {
    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(user.getUsername(), user.getPassword());
    }
});
session.setDebug(true);

try {
    MimeMessage msg = new MimeMessage(session);
    msg.setFrom(user.getUsername());

    msg.setRecipients(Message.RecipientType.TO,
            "some@mail.com");
    msg.setSubject("Testing SMTP using [" + user.getUsername() + "]");
    msg.setSentDate(new Date());
    msg.setText("Hey, this is a test from [" + user.getUsername() + "], Sending via Java Mail API");

    Transport.send(msg);
    System.out.println("Sent Ok");
} catch (MessagingException e) {
    System.out.println("Something went wrong");
    e.printStackTrace();
}
eyh26e7m

eyh26e7m1#

public class EWS {

    private static ExchangeService service;
    private static Integer NUMBER_EMAILS_FETCH = 5; // only latest 5 emails/appointments are fetched.

    static {
        try {
            service = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
            service.setUrl(new URI("https://outlook.office365.com/EWS/exchange.asmx"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Initialize the Exchange Credentials.
     */
    public EWS() throws Exception {
         ExchangeCredentials credentials = new WebCredentials("User Name", "Password");
        service.setCredentials(credentials);
    }

     /**
     * Reading one email at a time. Using Item ID of the email. Creating a
     * message data map as a return value.
     */
    public Map readEmailItem(ItemId itemId) {
        Map messageData = new HashMap();
        try {
            Item itm = Item.bind(service, itemId, PropertySet.FirstClassProperties);
            EmailMessage emailMessage = EmailMessage.bind(service, itm.getId());
            messageData.put("emailItemId", emailMessage.getId().toString());
            messageData.put("subject", emailMessage.getSubject());
            messageData.put("fromAddress", emailMessage.getFrom().getAddress());
            messageData.put("senderName", emailMessage.getSender().getName());
            Date dateTimeCreated = emailMessage.getDateTimeCreated();
            messageData.put("SendDate", dateTimeCreated.toString());
            Date dateTimeRecieved = emailMessage.getDateTimeReceived();
            messageData.put("RecievedDate", dateTimeRecieved.toString());
            messageData.put("Size", emailMessage.getSize() + "");
            messageData.put("emailBody", emailMessage.getBody().toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return messageData;
    }
    /**
     * Number of email we want to read is defined as NUMBER_EMAILS_FETCH,
     */
    public List<Map> readEmails() {
        List<Map> msgDataList = new ArrayList<>();
        try {
            service.setTraceEnabled(true);
            System.out.println("|---------------------> service = {}" + service);
            Folder folder = Folder.bind(service, WellKnownFolderName.Inbox);
            FindItemsResults<Item> results = service.findItems(folder.getId(), new ItemView(NUMBER_EMAILS_FETCH));
            int i = 1;
            for (Item item : results) {
                Map messageData = readEmailItem(item.getId());
                System.out.println("|---------------------> service = {}" + (i++) + ":");
                System.out.println("|---------------------> service = {}" + messageData.get("subject").toString());
                System.out.println("|---------------------> service = {}" + messageData.get("senderName").toString());
                msgDataList.add(messageData);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return msgDataList;
    }
    public static void main(String[] args) throws Exception {
        EWS msees = new EWS();
        List<Map> emails = msees.readEmails();
        System.out.println("|---------------------> service = {}" + emails.size());
    }
}
zf9nrax1

zf9nrax12#

在以下位置禁用STMP的现代身份验证:
https://admin.microsoft.com/Adminportal/Home?source=applauncher#/Settings/Services/:/Settings/L1/ModernAuthentication

请等待几分钟以测试是否进行了这些更改。

相关问题