简体   繁体   中英

Send Mail via Java Api for Office 365

Hi i am currently developing java application which will send mail to multiple recipients via Java Mail Api(1.6.2), i have configure the SMTP as per the Microsoft docs problem is the code is working with my personal hotmail email id but it fails for corporate office 365 account.

Error: javax.mail.AuthenticationFailedException: 535 5.7.3 Authentication unsuccessful [PN1PR0101CA0066.INDPRD01.PROD.OUTLOOK.COM]

POP and IMAP are working(Receiving mails) and i can login with the password in Office 365 Web, i have tried changing password too.

Code:

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();
}
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());
    }
}

Disable Modern authentication for STMP in:

https://admin.microsoft.com/Adminportal/Home?source=applauncher#/Settings/Services/:/Settings/L1/ModernAuthentication

未选中经过身份验证的 SMTP

Wait a few minutes to test making these changes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM