exchange 发送邮件

package com.example.demo.test;


import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import microsoft.exchange.webservices.data.core.ExchangeService;
import microsoft.exchange.webservices.data.core.enumeration.misc.ExchangeVersion;
import microsoft.exchange.webservices.data.core.exception.service.local.ServiceLocalException;
import microsoft.exchange.webservices.data.core.service.item.EmailMessage;
import microsoft.exchange.webservices.data.credential.ExchangeCredentials;
import microsoft.exchange.webservices.data.credential.WebCredentials;
import microsoft.exchange.webservices.data.property.complex.MessageBody;
/**
 * exchange协议发送邮件
 * @author peter
 *
 */
public class ExchangeClient {

   private static Log log = LogFactory.getLog(ExchangeClient.class);

    private final String hostname;
    private final ExchangeVersion exchangeVersion;
    private final String domain;
    private final String username;
    private final String password;
    private final String subject;
    private final List<String> recipientTo;
    private final List<String> recipientCc;
    private final List<String> recipientBcc;
    private final List<String> attachments;
    private final String message;

    private ExchangeClient(ExchangeClientBuilder builder) {
        this.hostname = builder.hostname;
        this.exchangeVersion = builder.exchangeVersion;
        this.domain = builder.domain;
        this.username = builder.username;
        this.password = builder.password;
        this.subject = builder.subject;
        this.recipientTo = builder.recipientTo;
        this.recipientCc = builder.recipientCc;
        this.recipientBcc = builder.recipientBcc;
        this.attachments = builder.attachments;
        this.message = builder.message;
    }

    public static class ExchangeClientBuilder {

        private String hostname;
        private ExchangeVersion exchangeVersion;
        private String domain;
        private String username;
        private String password;
        private String subject;
        private List<String> recipientTo;
        private List<String> recipientCc;
        private List<String> recipientBcc;
        private List<String> attachments;
        private String message;

        public ExchangeClientBuilder() {
            this.exchangeVersion = ExchangeVersion.Exchange2010_SP1;
            this.hostname = "";
            this.username = "";
            this.password = "";
            this.subject = "";
            this.recipientTo = new ArrayList<>(0);
            this.recipientCc = new ArrayList<>(0);
            this.recipientBcc = new ArrayList<>(0);
            this.attachments = new ArrayList<>(0);
            this.message = "";
        }

        /**
         * The hostname of the Exchange Web Service. It will be used for
         * connecting with URI https://hostname/ews/exchange.asmx
         *
         * @param hostname the hostname of the MS Exchange Smtp Server.
         * @return the builder for chain usage.
         */
        public ExchangeClientBuilder hostname(String hostname) {
            this.hostname = hostname;
            return this;
        }

        /**
         * The Exchange Web Server version.
         *
         * @param exchangeVersion the Exchange Web Server version.
         * @return the builder for chain usage.
         */
        public ExchangeClientBuilder exchangeVersion(ExchangeVersion exchangeVersion) {
            this.exchangeVersion = exchangeVersion;
            return this;
        }

        /**
         * The domain of the MS Exchange Smtp Server.
         *
         * @param domain the domain of the Active Directory. The first part of
         * the username. For example: MYDOMAIN\\username, set the MYDOMAIN.
         * @return the builder for chain usage.
         */
        public ExchangeClientBuilder domain(String domain) {
            this.domain = domain;
            return this;
        }

        /**
         * The username of the MS Exchange Smtp Server. The second part of the
         * username. For example: MYDOMAIN\\username, set the username.
         *
         * @param username the username of the MS Exchange Smtp Server.
         * @return the builder for chain usage.
         */
        public ExchangeClientBuilder username(String username) {
            this.username = username;
            return this;
        }

        /**
         * The password of the MS Exchange Smtp Server.
         *
         * @param password the password of the MS Exchange Smtp Server.
         * @return the builder for chain usage.
         */
        public ExchangeClientBuilder password(String password) {
            this.password = password;
            return this;
        }

        /**
         * The subject for this send.
         *
         * @param subject the subject for this send.
         * @return the builder for chain usage.
         */
        public ExchangeClientBuilder subject(String subject) {
            this.subject = subject;
            return this;
        }

        /**
         * The recipient for this send.
         *
         * @param recipientTo the recipient for this send.
         * @return the builder for chain usage.
         */
        public ExchangeClientBuilder recipientTo(String recipientTo) {
            this.recipientTo = Arrays.asList(recipientTo.split(","));
            return this;
        }

        /**
         * You can specify one or more email address that will be used as cc
         * recipients.
         *
         * @param recipientCc the first cc email address.
         * @param recipientsCc the other cc email address for this send.
         * @return the builder for chain usage.
         */
        public ExchangeClientBuilder recipientCc(String recipientCc, String... recipientsCc) {
            // Prepare the list.
            List<String> recipients = new ArrayList<>(1 + recipientsCc.length);
            recipients.add(recipientCc);
            recipients.addAll(Arrays.asList(recipientsCc));
            // Set the list.
            this.recipientCc = recipients;
            return this;
        }

        /**
         * You can specify a list with email addresses that will be used as cc
         * for this email send.
         *
         * @param recipientCc the list with email addresses that will be used as
         * cc for this email send.
         * @return the builder for chain usage.
         */
        public ExchangeClientBuilder recipientCc(List<String> recipientCc) {
            this.recipientCc = recipientCc;
            return this;
        }

        /**
         * You can specify one or more email address that will be used as bcc
         * recipients.
         *
         * @param recipientBcc the first bcc email address.
         * @param recipientsBcc the other bcc email address for this send.
         * @return the builder for chain usage.
         */
        public ExchangeClientBuilder recipientBcc(String recipientBcc, String... recipientsBcc) {
            // Prepare the list.
            List<String> recipients = new ArrayList<>(1 + recipientsBcc.length);
            recipients.add(recipientBcc);
            recipients.addAll(Arrays.asList(recipientsBcc));
            // Set the list.
            this.recipientBcc = recipients;
            return this;
        }

        /**
         * You can specify a list with email addresses that will be used as bcc
         * for this email send.
         *
         * @param recipientBcc the list with email addresses that will be used
         * as bcc for this email send.
         * @return the builder for chain usage.
         */
        public ExchangeClientBuilder recipientBcc(List<String> recipientBcc) {
            this.recipientBcc = recipientBcc;
            return this;
        }

        /**
         * You can specify one or more email address that will be used as cc
         * recipients.
         *
         * @param attachment the first attachment.
         * @param attachments the other attachments for this send.
         * @return the builder for chain usage.
         */
        public ExchangeClientBuilder attachments(String attachment, String... attachments) {
            // Prepare the list.
            List<String> attachmentsToUse = new ArrayList<>(1 + attachments.length);
            attachmentsToUse.add(attachment);
            attachmentsToUse.addAll(Arrays.asList(attachments));
            // Set the list.
            this.attachments = attachmentsToUse;
            return this;
        }

        /**
         * You can specify a list with email attachments that will be used for
         * this email send.
         *
         * @param attachments the list with email attachments that will be used
         * for this email send.
         * @return the builder for chain usage.
         */
        public ExchangeClientBuilder attachments(List<String> attachments) {
            this.attachments = attachments;
            return this;
        }

        /**
         * The body of the email message.
         *
         * @param message the body of the email message.
         * @return the builder for chain usage.
         */
        public ExchangeClientBuilder message(String message) {
            this.message = message;
            return this;
        }

        /**
         * Build a mail.
         *
         * @return an EmailApacheUtils object.
         */
        public ExchangeClient build() {
            return new ExchangeClient(this);
        }
    }

    public boolean sendExchange() {
        // The Exchange Server Version.
        ExchangeService exchangeService = new ExchangeService(exchangeVersion);

        // Credentials to sign in the MS Exchange Server.
        ExchangeCredentials exchangeCredentials = new WebCredentials(username, password, domain);
        exchangeService.setCredentials(exchangeCredentials);

        // URL of exchange web service for the mailbox.
        try {
            exchangeService.setUrl(new URI("https://" + hostname + "/ews/Exchange.asmx"));
        } catch (URISyntaxException ex) {
            log.info("An exception occured while creating the uri for exchange service.", ex);
            return false;
        }

        // The email.
        EmailMessage emailMessage;
        try {
            emailMessage = new EmailMessage(exchangeService);
            emailMessage.setSubject(subject);
            emailMessage.setBody(MessageBody.getMessageBodyFromText(message));
        } catch (Exception ex) {
            log.info("An exception occured while setting the email message.", ex);
            return false;
        }

        // TO recipient.
        for(String recipient : recipientTo){
           try {
                emailMessage.getToRecipients().add(recipient);
            } catch (ServiceLocalException ex) {
                log.info("An exception occured while sstting the TO recipient(" + recipientTo + ").", ex);
                return false;
            }
        }

        // CC recipient.
        for (String recipient : recipientCc) {
            try {
                emailMessage.getCcRecipients().add(recipient);
            } catch (ServiceLocalException ex) {
                log.info("An exception occured while sstting the CC recipient(" + recipient + ").", ex);
                return false;
            }
        }

        // BCC recipient
        for (String recipient : recipientBcc) {
            try {
                emailMessage.getBccRecipients().add(recipient);
            } catch (ServiceLocalException ex) {
                log.info("An exception occured while sstting the BCC recipient(" + recipient + ").", ex);
                return false;
            }
        }

        // Attachements.
        for (String attachmentPath : attachments) {
            try {
                emailMessage.getAttachments().addFileAttachment(attachmentPath);
            } catch (ServiceLocalException ex) {
                log.info("An exception occured while setting the attachment.", ex);
                return false;
            }
        }

        try {
            emailMessage.send();
            log.info("An email is send.");
        } catch (Exception ex) {
            log.info("An exception occured while sending an email.", ex);
            return false;
        }

        return true;
    }

}

调用代码

package com.example.demo.test;

import microsoft.exchange.webservices.data.core.enumeration.misc.ExchangeVersion;
import org.springframework.beans.factory.annotation.Autowired;

public class ExchangeEmail {


    @Autowired
    public SendEmailUtil emailUtil;

    private static String account = "xxxxxxx@outlook.com";
    private static String pass = "xxxxxxxxx";
    private static String host = "outlook.office365.com";

    public static void main(String[] args) {
        ExchangeClient client = new ExchangeClient.ExchangeClientBuilder()
                .hostname(host)
                .exchangeVersion(ExchangeVersion.Exchange2010)
                .username(account)
                .password(pass)
                .recipientTo("xxx")
                .recipientBcc("ss","ff","ddff","sef","dfe")
                .subject("Test Subject")
                .message("Test Message")
                .build();
        client.sendExchange();
    }
}

 

这是从网上找来的工具类,确认没问题。可以使用。对我需要的地方做了修改。

刚开始使用的qq的exchange服务器。ex.qq.com

发现报错ssl安全认证报错。导入认证在浏览器地址栏输入   https://ex.exmail.qq.com/EWS/exchange.asmx

具体操作 : https://blog.csdn.net/Peter_S/article/details/97649729

之后报错,请求失败,报错400.才发现qq的exchange服务器挂了。后来上网搜索了outlook邮箱。通过outlook邮箱测试。

下面这个是我搜搜outlook exchange服务器地址发现的,很有用。直接粘贴过来了。

------------------------------------------------------------------------------------

查找 Exchange 服务器名称
  如果您的电子邮件程序无法自动查找您的 Exchange ActiveSync 服务器名称,您可能需要手动查找。
  如果您连接的是 Office 365 电子邮件,请将 outlook.office365.com 用作 Exchange ActiveSync 服务器名称
  如果您正连接到 Exchange 邮箱但未使用 Office 365,或者您不确定使用的是否是 Office 365,请按照这些步骤查找您的 Exchange ActiveSync 服务器名称。
  使用 Outlook Web App 来登录到您的帐户。 有关登录帮助,请参阅登录到 Outlook Web App。
  如果您正连接到 Exchange 邮箱但未使用 Office 365,则您登录到 Outlook Web App 之后,浏览器的地址栏中将包含您的 Exchange ActiveSync 服务器名称,但不带前导 https:// 和尾部 /owa。例如,如果用于访问 Outlook Web App 的地址是 https://mail.contoso.com/owa,则您的 Exchange ActiveSync 服务器名称是mail.contoso.com。
  如果您无法使用本节前面的信息连接到您的邮箱,则可以尝试使用您可以在 Outlook Web App 选项中查看的服务器名称值。
  在 Outlook Web App 中的工具栏上,单击“设置” >“选项”>“帐户”>“我的帐户”>“POP 和 IMAP 访问的设置”。
  注意 尽管您不是在设置 POP3 帐户,但您仍将使用该值来确定您的 Exchange ActiveSync 服务器名称。
  在“POP 设置”下,查看“服务器名称”的值。
  如果“服务器名称”值为“outlook.office365.com”,则说明您的帐户在 Office 365 工作或学校帐户 中,因此您可将 outlook.office365.com 用作 Exchange 服务器名称。
  如果“服务器名称”值不是“outlook.office365.com”,您可以尝试使用选项页上列出的服务器名称。例如,如果服务器名称是 mail.contoso.com,请尝试使用 mail.contoso.com 作为您的 Exchange 服务器名称。

连接 : https://zhidao.baidu.com/question/426676191.html

--------------------------------------------------------------------------------------------------------------------

之后在客户Linux系统测试,发信报错。

The remote server returned an error: (401) Unauthorized 

这个我是账号密码写错了,所以导致的这个问题,多了空格,尴尬

Android Exchange 协议是一种用于在 Android 设备上发送和接收邮件的通信协议。它基于 Microsoft Exchange Server,并使用 Microsoft Exchange ActiveSync(EAS)进行通信。 Android Exchange 协议提供了以下功能和特点: 1. 邮件发送:Android Exchange 协议允许用户通过 Android 设备发送电子邮件。用户可以通过设备上的电子邮件应用程序编写邮件,选择收件人,并附加文件或图片。 2. 邮件同步:Android Exchange 协议通过与 Exchange Server 进行实时同步,确保所有邮件状态和操作在设备和服务器之间保持同步。这意味着,无论是通过设备还是服务器上的应用程序进行的操作,都会即时反映在另一端。 3. 日历和联系人同步:除了邮件,Android Exchange 协议还支持日历和联系人同步。用户可以在设备上查看和编辑 Exchange Server 上的日历事件和联系人信息,并确保更新会自动同步到服务器和其他设备上。 4. 安全性:Android Exchange 协议使用 Microsoft Exchange ActiveSync(EAS)进行通信,并支持加密和远程设备管理功能,以保护邮件的安全和用户的隐私。用户可以远程擦除设备上的数据,设置密码策略,并进行远程锁屏等操作。 综上所述, Android Exchange 协议为 Android 设备的用户提供了便捷的邮件发送和接收功能,并确保邮件、日历和联系人的同步和安全。无论是个人用户还是企业用户,都能从这一协议中受益,以更高效和安全的方式管理和处理电子邮件。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值