java傳送郵件功能,以傳送qq郵件為例
阿新 • • 發佈:2022-04-29
問題①: java傳送qq郵件出現如下錯誤的解決方法:
503 Error: need EHLO and AUTH first !
pop.put("mail.smtp.auth", "true");//注意value值不能不設定,並且不能是Boolean型別,應為字串,否則會報如上所示錯誤
問題②: Could not connect to SMTP host: smtp.qq.com, port: 465, response: -1
原因:
465埠是為SMTPS(SMTP-over-SSL)協議服務開放的,這是SMTP協議基於SSL安全協議之上的一種變種協議.
解決方法:
配置檔案需要加上如下程式碼即可解決.
pop.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
附上所有的程式碼:
配置檔案:
mail: mailhost: smtp.qq.com mailport: 465 user: 郵箱使用者名稱 password: 密碼(qq為授權碼) mailFrom: [email protected] mailTo: [email protected],[email protected],[email protected] properties: mail: smtp: auth: true mailtimeout: 1000 mailssl: javax.net.ssl.SSLSocketFactory starttls: enable: true required: true
java程式碼:
@Value("${mailhost}") private String host; @Value("${mailport}") private Integer port; @Value("${user}") private String username; @Value("${password}") private String password; @Value("${mailFrom}") private String from; @Value("${mailTo}") private String [] to; @Value("${auth}") private String auth; @Value("${enable}") private Boolean enable; @Value("${required}") private Boolean required; @Value("${mailtimeout}") private Integer timeout; @Value("${mailssl}") private String ssl; public void onApplicationEvent(ApplicationEvent event) { System.out.println("email cfg...."); System.out.println("print:"+this.toString()); //建立一個傳送者物件 JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); mailSender.setHost(this.host); mailSender.setPort(this.port); mailSender.setUsername(this.username); mailSender.setPassword(this.password); // 加認證機制 Properties pop = new Properties(); pop.put("mail.smtp.host", this.host); // pop.put("mail.smtp.port", this.port);//已經在上面加過 pop.put("mail.smtp.auth", this.auth);//必須是字串而不能是boolean否則報錯 pop.put("mail.smtp.starttls.enable", this.enable); pop.put("mail.smtp.timeout", this.timeout); pop.put("mail.smtp.socketFactory.class", this.ssl); mailSender.setJavaMailProperties(pop); //組織郵件引數並執行傳送 SimpleMailMessage message = new SimpleMailMessage(); message.setFrom(this.from); message.setTo(this.to); message.setSubject("主題:測試,spring boot傳送郵件."); message.setText("測 試n 郵件為程式傳送,是否收到?請回答"); mailSender.send(message); System.out.println("send end...."); } @Override public String toString() { return "EmailConfiguration [host=" + host + ", port=" + port + ", username=" + username + ", password=" + password + ", from=" + from + ", to=" + to + ", auth=" + auth + ", enable=" + enable + ", required=" + required + ", timeout=" + timeout + "]"; }