web-dev-qa-db-ja.com

MS Exchangeサーバーを使用してメールを送信する方法

会社のメールサーバーを使用してメールを送信しようとしています。しかし、私は次の例外を受けています

Caused by: com.Sun.mail.smtp.SMTPSendFailedException: 530 5.7.1 Client was not authenticated
    at com.Sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.Java:1388)
    at com.Sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.Java:959)
    at com.Sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.Java:583)
    at javax.mail.Transport.send0(Transport.Java:169)
    at javax.mail.Transport.send(Transport.Java:98)

これが私のサンプルコードです、

Properties props = System.getProperties();

// Setup mail server
props.put("mail.smtp.Host", "example.server.com");
props.put("mail.smtp.auth", "true");
props.put("mail.debug", "true");
props.put("mail.smtp.port", "25");
// Get session
//Session session = Session.getDefaultInstance(props, null);
Session session = Session.getDefaultInstance(props,
    new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("username", "password");
        }
    });

// Define message
MimeMessage message = new MimeMessage(session);

// Set the from address
message.setFrom(new InternetAddress(from));

// Set the to address
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

// Set the subject
message.setSubject("Hello JavaMail");

// Set the content
message.setText("Welcome to JavaMail");

// Send message
Transport.send(message);

間違っているコードは何ですか?ユーザー名とパスワードと同様に、会社のメールアドレスとパスワードを使用しています。

11
user509755

5.7.1はおそらく交換ではなくコードによって引き起こされます。サーバーでリレーを有効にする必要があるだけかもしれません。匿名ユーザーまたは特定のIPアドレスから。私はExchangeの専門家ではありませんが、これは以前から機能しています。これが私がテストした最後のソリューションです。

ユーザーが認証されたときに、ExchangeサーバーでSMTP経由で電子メールを送信しようとしたときに5.7.1エラーが発生した場合。

Refの問題は、Exchange 2007サーバーの設定が原因で発生しました。これは通常、2003サーバーの問題ではありません。

以下を実行して修正...

この認証設定はGUIで設定できます

  • サーバー構成/ハブトランスポート/デフォルト<サーバー名>
  • 右クリック、プロパティ、権限グループ
  • 「匿名ユーザー」にチェックを入れて、「OK」をクリックします

明らかにanonユーザーは安全ではありませんが、これで問題が解決するかどうかを確認できます。

6
WraithNath

MS Exhange SMTPサーバーを使用してメールを送信する場合、上記のmaven依存関係を使用します。

<dependency>
    <groupId>com.Microsoft.ews-Java-api</groupId>
    <artifactId>ews-Java-api</artifactId>
    <version>2.0</version>
</dependency>

そのため、MS Exchangeサーバーの電子メールクライアントを表すクラスを作成しました。ロギングにはlog4jを使用します。

<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>

MS Exchangeクライアントクラスの下(スレッドセーフのためのオブジェクトの構築にビルダーパターンを使用)、

import Java.net.URI;
import Java.net.URISyntaxException;
import Java.util.ArrayList;
import Java.util.Arrays;
import Java.util.List;
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;
import org.Apache.log4j.Logger;

/**
 * A client to connect to a MS Exchange SMTP Server.
 */
public final class ExchangeClient {

    private static final Logger LOGGER = Logger.getLogger(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 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 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 = "";
            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 = recipientTo;
            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) {
            LOGGER.error("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) {
            LOGGER.error("An exception occured while setting the email message.", ex);
            return false;
        }

        // TO recipient.
        try {
            emailMessage.getToRecipients().add(recipientTo);
        } catch (ServiceLocalException ex) {
            LOGGER.error("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) {
                LOGGER.error("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) {
                LOGGER.error("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) {
                LOGGER.error("An exception occured while setting the attachment.", ex);
                return false;
            }
        }

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

        return true;
    }

}

実例、

// import Microsoft.exchange.webservices.data.core.enumeration.misc.ExchangeVersion;
ExchangeClient client = new ExchangeClient.ExchangeClientBuilder()
        .hostname("webmail.domainOfWeb.com")
        .exchangeVersion(ExchangeVersion.Exchange2010)
        .domain("ActiveDirectoryDomain")
        .username("ActiveDirectoryUsername")
        .password("ActiveDirectoryPassword")
        .recipientTo("[email protected]")
        .recipientCc("[email protected]") // Ignore it in case you will not use Cc recipients.
        .recipientBcc("[email protected]") // Ignore it in case you will not use Bcc recipients.
        .attachments("/home/username/image.png") // Ignore it in case you will not use attachements.
        .subject("Test Subject")
        .message("Test Message")
        .build();
client.sendExchange();
4

Mail.jar(バージョン1.4.0)にはMS Exchange Serverとの互換性の問題があり、ユーザー名とパスワードが設定されている場合でも530 5.7.1 Client was not authenticatedをスローします。

メールAPIを1.4.4にアップグレードするOR 1.4.7で問題が解決するはずです。

Mail APIの1.4.7は、次のURLからダウンロードできます。 http://www.Oracle.com/technetwork/Java/javamail/index.html

2
Kamran

一部の企業では、ExchangeサーバーのSMTPサポートが無効になっていて、有効にするように依頼することができません。これらの場合、合理的な解決策は次のとおりです。

http://davmail.sourceforge.net/

2
BrunoJCM

私はjavamail + exchangeを使わなければなりませんでした。返されたメッセージは無力でした。スタックのおかげで、いくつかのヒントを得ました。

これをコードに追加します

  props.put("mail.smtp.starttls.enable","true");

使用するマシンの証明書も追加することを考えてください。それらを見つけるには、ブラウザに移動してエクスポートし、使用中のcacertsファイルにインポートします。

1
Jerome_B

Simple Java Mail は私のために働きました。チェックする必要があるのは正しいhostnameusernameportおよびpasswordTransportStrategy.SMTP_TLS

new Mailer(Host, port, username, password, TransportStrategy.SMTP_TLS).sendMail(email);
1
zeddarn

Transport.send(message);の代わりに次のコード部分を使用してください

MimeMessage message = new MimeMessage(session);

message.saveChanges();
Transport transport = session.getTransport("smtp");
transport.connect(Host, "user", "pwd");
transport.sendMessage(message, message.getAllRecipients());
transport.close();

私はローカルでテストしました、そしてそれは働いています

0
Ming Jiang