exchange 发送邮件

本文介绍了一个使用Exchange协议发送邮件的实用工具类,详细展示了如何配置Exchange服务器参数,包括主机名、版本、用户名、密码等,并提供了代码示例。同时,文章记录了作者在使用QQ和Outlook 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.youkuaiyun.com/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 

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

在Go语言中,通过Exchange服务器发送邮件通常需要使用支持SMTP协议的客户端。Exchange服务器可以通过SMTP协议进行邮件发送,因此可以通过配置SMTP客户端连接到Exchange服务器并发送邮件。以下是实现这一功能的详细步骤。 首先,需要导入必要的库。Go标准库中没有直接支持Exchange邮件发送功能,但可以使用第三方库如`github.com/jordan-wright/email`或`github.com/xhit/go-simple-mail/v2`来实现邮件发送功能。以下是一个使用`github.com/xhit/go-simple-mail/v2`库的示例代码: ```go package main import ( "log" "github.com/xhit/go-simple-mail/v2" ) func main() { // 创建一个新的SMTP客户端配置 server := mail.NewSMTPClient() server.Host = "smtp.exchange.com" // Exchange邮件服务地址 server.Port = 587 // Exchange SMTP端口 server.Username = "user@exchange.com" server.Password = "password" server.Encryption = mail.EncryptionTLS // 使用TLS加密 // 连接到SMTP服务器 smtpClient, err := server.Connect() if err != nil { log.Fatal(err) } // 创建邮件对象 email := mail.NewMSG() email.SetFrom("发件人昵称<user@exchange.com>") email.AddTo("收件人邮箱") email.SetSubject("测试主题") // 设置邮件正文 str := `我是测试内容` email.SetBody(mail.TextPlain, str) // 发送邮件 err = email.Send(smtpClient) if err != nil { log.Fatal(err) } log.Println("发送成功") } ``` 上述代码中,首先创建了一个SMTP客户端配置,指定了Exchange服务器的地址、端口、用户名和密码,并设置了加密方式为TLS。接着,通过调用`Connect()`方法连接到SMTP服务器。之后,创建了一个邮件对象,并设置了发件人、收件人、主题和正文。最后,通过调用`Send()`方法发送邮件。 需要注意的是,在使用Exchange服务器发送邮件时,必须确保服务器允许通过SMTP协议发送邮件,并且正确配置了相关设置。此外,还需要确保使用的账户具有发送邮件的权限。如果Exchange服务器配置了特定的安全策略,可能还需要调整代码中的加密方式或端口号以适应实际环境。 如果遇到连接问题,可以检查网络配置是否正确,以及Exchange服务器是否接受来自客户端的SMTP请求。对于某些企业级Exchange服务器,可能还需要额外的认证步骤或使用特定的端口(如465或587)来发送邮件。 通过以上步骤,可以在Go语言中实现通过Exchange服务器发送邮件的功能[^3]。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值