首页 » 技术分享 » java mail 使用:exchange邮箱

java mail 使用:exchange邮箱

 

第一次使用java mail 写发邮件的程序,我是使用maven来构建依赖的

这里不描述怎么使用java mail发邮件,主要描述如何使用exchange .由于公司邮箱是用的是exchange ,我百度好久也没有合适的说明使用,绕了好多弯路,故在此记录,以便他人少走弯路。
我在一篇文章中发现exchange邮箱需要加域,一般都是domain\username,但是使用后发现会报“AuthenticationFailedException: 535 5.7.3 Authentication unsuccessful”用户名密码错误,找了好久没有办法解决,但是从本质上想,想有没有“域”的参数,找来找去找到的相应的api。
http://www.yiibai.com/javamail_api/javamail_api_smtp_servers.html
需要添加mail.smtp.auth.ntlm.domain参数,
props.setProperty("mail.smtp.auth.ntlm.domain", domain);果然一试就成功了。
<dependency>
    <groupId>javax.mail</groupId>
    <artifactId>mail</artifactId>
    <version>1.5.0-b01</version>
</dependency>
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Properties;
import java.util.Vector;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.AuthenticationFailedException;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

/**
 * 
 * @author laughing 
 * @from http://www.yiibai.com/javamail_api/javamail_api_smtp_servers.html
 *
 */
public class MailTool {
    // 定义发件人、收件人、SMTP服务器、用户名、密码、主题、内容等
    private String displayName;
    private String to;
    private String from;
    private String smtpServer;
    private String username;
    private String password;
    private String subject;
    private String content;
    private boolean isExchange = false;
    private String domain ;
    private boolean ifAuth; // 服务器是否要身份认证
    private String filename = "";
    private Vector<String> file = new Vector<String>(); // 用于保存发送附件的文件名的集合

    /**
     * 设置SMTP服务器地址
     */
    public void setSmtpServer(String smtpServer) {
        this.smtpServer = smtpServer;
    }

    /**
     * 设置发件人的地址
     */
    public void setFrom(String from) {
        this.from = from;
    }

    /**
     * 设置显示的名称
     */
    public void setDisplayName(String displayName) {
        this.displayName = displayName;
    }

    /**
     * 设置服务器是否需要身份认证
     */
    public void setIfAuth(boolean ifAuth) {
        this.ifAuth = ifAuth;
    }

    /**
     * 设置E-mail用户名
     */
    public void setUserName(String username) {
        this.username = username;
    }

    /**
     * 设置E-mail密码
     */
    public void setPassword(String password) {
        this.password = password;
    }

    /**
     * 设置接收者
     */
    public void setTo(String to) {
        this.to = to;
    }

    /**
     * 设置主题
     */
    public void setSubject(String subject) {
        this.subject = subject;
    }

    /**
     * 设置主体内容
     */
    public void setContent(String content) {
        this.content = content;
    }


    public boolean isExchange() {
        return isExchange;
    }

    public void setExchange(boolean isExchange) {
        this.isExchange = isExchange;
    }

    // 域设置
    public String getDomain() {
        return domain;
    }

    public void setDomain(String domain) {
        this.domain = domain;
    }

    /**
     * 该方法用于收集附件名
     */
    public void addAttachfile(String fname) {
        file.addElement(fname);
    }

    public MailTool() {

    }



    /**
     * 初始化SMTP服务器地址、发送者E-mail地址、接收者、主题、内容
     */
    public MailTool(String smtpServer, String from, String displayName, String to,
            String subject, String content ,boolean isExchange, String domain) {
        this.smtpServer = smtpServer;
        this.from = from;
        this.displayName = displayName;
        this.ifAuth = false;
        this.to = to;
        this.subject = subject;
        this.content = content;
        this.isExchange = isExchange;
        this.domain = domain;
    }

    /**
     * 发送邮件
     */
    public HashMap<String, String> send() {
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("state", "success");
        String message = "邮件发送成功!";
        Session session = null;
        Properties props = System.getProperties();
        props.put("mail.smtp.host", smtpServer);

        if(isExchange){
            if(domain == null || domain.equals("")){
                throw new RuntimeException("domain is null");
            }
            props.setProperty("mail.smtp.auth.ntlm.domain", domain);
        }
        if (ifAuth) { // 服务器需要身份认证
            props.put("mail.smtp.auth", "true");
            MailAuthenticator smtpAuth = new MailAuthenticator(username, password);
            session = Session.getDefaultInstance(props, smtpAuth);
        } else {
            props.put("mail.smtp.auth", "false");
            session = Session.getDefaultInstance(props, null);
        }
        session.setDebug(true);
        Transport trans = null;
        try {
            Message msg = new MimeMessage(session);
            try {
                Address from_address = new InternetAddress(from, displayName);
                msg.setFrom(from_address);
            } catch (java.io.UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            InternetAddress[] address = { new InternetAddress(to) };
            msg.setRecipients(Message.RecipientType.TO, address);
            msg.setSubject(subject);
            Multipart mp = new MimeMultipart();
            MimeBodyPart mbp = new MimeBodyPart();
            mbp.setContent(content.toString(), "text/html;charset=gb2312");
            mp.addBodyPart(mbp);
            if (!file.isEmpty()) {// 有附件
                Enumeration<String> efile = file.elements();
                while (efile.hasMoreElements()) {
                    mbp = new MimeBodyPart();
                    filename = efile.nextElement().toString(); // 选择出每一个附件名
                    FileDataSource fds = new FileDataSource(filename); // 得到数据源
                    mbp.setDataHandler(new DataHandler(fds)); // 得到附件本身并至入BodyPart
                    mbp.setFileName(fds.getName()); // 得到文件名同样至入BodyPart
                    mp.addBodyPart(mbp);
                }
                file.removeAllElements();
            }
            msg.setContent(mp); // Multipart加入到信件
            msg.setSentDate(new Date()); // 设置信件头的发送日期
            // 发送信件
            msg.saveChanges();
            trans = session.getTransport("smtp");
            trans.connect(smtpServer, username, password);
            trans.sendMessage(msg, msg.getAllRecipients());
            trans.close();

        } catch (AuthenticationFailedException e) {
            map.put("state", "failed");
            message = "邮件发送失败!错误原因:\n" + "身份验证错误!";
            e.printStackTrace();
        } catch (MessagingException e) {
            message = "邮件发送失败!错误原因:\n" + e.getMessage();
            map.put("state", "failed");
            e.printStackTrace();
            Exception ex = null;
            if ((ex = e.getNextException()) != null) {
                System.out.println(ex.toString());
                ex.printStackTrace();
            }
        }
        // System.out.println("\n提示信息:"+message);
        map.put("message", message);
        return map;
    }

    public static void main(String[] args) {
        String smtpServer = "exchange.be***.com.cn";
        String from = "*******@be***.com.cn";
        String userName = "*******";
        String password = "*******";
        String to = "*******@qq.com";
        String subject = "你好";
        String content = "你好啊";
        MailTool mail = new MailTool(smtpServer, from, "BES**YDJD", userName, password,
                to, subject, content);
        mail.send();
    }
}
package tool.mail;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;

/**
 * 
 * 服务器邮箱登录验证
 *  
 */

public class MailAuthenticator extends Authenticator {

    /**
     * 
     * 用户名(登录邮箱)
     */

    private String username;
    /**
     * 密码
     */
    private String password;

    /**
     * 
     * 初始化邮箱和密码
     * 
     * @param username
     *            邮箱
     * 
     * @param password
     *            密码
     */
    public MailAuthenticator(String username, String password) {
        this.username = username;
        this.password = password;
    }

    String getPassword() {
        return password;
    }

    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(username, password);
    }

    String getUsername() {
        return username;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void setUsername(String username) {
        this.username = username;
    }

}

转载自原文链接, 如需删除请联系管理员。

原文链接:java mail 使用:exchange邮箱,转载请注明来源!

0