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;
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM