我正在嘗試通過 Gmail 發送電子郵件,但出現例外“未知 SMTP 主機:smtp.gmail.com ”。我已經打開了不太安全的應用程式訪問,應該關閉兩步驗證。
public class MonitoringMail
{
public void sendMail(String mailServer, String from, String[] to, String subject, String messageBody) throws MessagingException, AddressException
{
boolean debug = false;
Properties props = new Properties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.EnableSSL.enable","true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", mailServer);
props.put("mail.debug", "true");
props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.port", "465");
props.setProperty("mail.smtp.socketFactory.port", "465");
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getDefaultInstance(props, auth);
session.setDebug(debug);
try
{
Transport bus = session.getTransport("smtp");
bus.connect();
Message message = new MimeMessage(session);
//X-Priority values are generally numbers like 1 (for highest priority), 3 (normal) and 5 (lowest).
message.addHeader("X-Priority", "1");
message.setFrom(new InternetAddress(from));
InternetAddress[] addressTo = new InternetAddress[to.length];
for (int i = 0; i < to.length; i )
addressTo[i] = new InternetAddress(to[i]);
message.setRecipients(Message.RecipientType .TO, addressTo);
message.setSubject(subject);
BodyPart body = new MimeBodyPart();
// body.setText(messageBody);
body.setContent(messageBody,"text/html");
MimeMultipart multipart = new MimeMultipart();
multipart.addBodyPart(body);
// multipart.addBodyPart(attachment);
message.setContent(multipart);
Transport.send(message);
System.out.println("Sucessfully Sent mail to All Users");
bus.close();
}
catch (MessagingException mex)
{
mex.printStackTrace();
}
}
它作業得更早,但一周后我得到了一個例外。我嘗試解決此例外,我花了 3 天時間但無法解決這些問題,請嘗試解決此問題。
uj5u.com熱心網友回復:
SMTP 有 2 個不同的埠 用于SSL 的埠 465 用于TLS/STARTTLS 的埠587 您是否嘗試過使用其他埠?
uj5u.com熱心網友回復:
請嘗試使用埠 25。
props.setProperty("mail.smtp.port", "25");
uj5u.com熱心網友回復:
我了解到您已經設定了 Gmail 帳戶并啟用了安全性較低的應用,但 Gmail 帳戶在一段時間不活動后會自動關閉“允許安全性較低的應用”選項。如果此代碼以前有效,請嘗試再次檢查您的 Gmail 帳戶設定。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/383255.html
