javamail发送邮件及错误解决方法javax.mail.AuthenticationFailedException: failed to connect, no password specified?

javamail发送邮件及错误解决方法javax.mail.AuthenticationFailedException: failed to connect, no password specified?

一、继承Authenticator

二、重写protected PasswordAuthentication getPasswordAuthentication() {}方法,获取到传入的usernam,password

三、new对象的时候传入usernam,password :authenticator = new MailAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());

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

public class MailAuthenticator extends Authenticator {
    private String strUser;
    private String strPwd;

    public MailAuthenticator() {
        super();
    }

    @Override
    public PasswordAuthentication getPasswordAuthentication() {
        String username = this.strUser;
        String password = this.strPwd;
        if ((username != null) && (username.length() > 0) && (password != null) && (password.length() > 0)) {

            return new PasswordAuthentication(username, password);
        }

        return null;
    }

    public MailAuthenticator(String user, String password) {
        this.strUser = user;
        this.strPwd = password;
    }
}
public boolean sendTextMail(MailSenderInfo mailInfo) {
        // 判断是否需要身份认证
        MailAuthenticator authenticator = null;
        Properties pro = mailInfo.getProperties();
        if (mailInfo.isValidate()) {
            // 如果需要身份认证,则创建一个密码验证器
            authenticator = new MailAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
        }
        // 根据邮件会话属性和密码验证器构造一个发送邮件的session
        Session sendMailSession = Session.getDefaultInstance(pro, authenticator);
        try {
            // 根据session创建一个邮件消息
            Message mailMessage = new MimeMessage(sendMailSession);
            // 创建邮件发送者地址
            Address from = new InternetAddress(mailInfo.getFromAddress());
            // 设置邮件消息的发送者
            mailMessage.setFrom(from);
            // 创建邮件的接收者地址,并设置到邮件消息中
            Address to = new InternetAddress(mailInfo.getToAddress());
            mailMessage.setRecipient(Message.RecipientType.TO, to);
            // 设置邮件消息的主题
            mailMessage.setSubject(mailInfo.getSubject());
            // 设置邮件消息发送的时间
            mailMessage.setSentDate(new Date());
            // 设置邮件消息的主要内容
            String mailContent = mailInfo.getContent();
            mailMessage.setText(mailContent);
            // 发送邮件
            Transport.send(mailMessage);
            return true;
        } catch (MessagingException ex) {
            ex.printStackTrace();
        }
        return false;
    }

 

posted @ 2018-08-20 18:10  大自然的流风  阅读(10815)  评论(0编辑  收藏  举报