[英]Simple Java mail program is not working?
我想知道為什么下面的基本 java 郵件程序不起作用,因為我沒有收到任何錯誤,因為程序執行得很好。 有什么我做錯了嗎? 任何幫助將不勝感激。我還想補充一點,我也使用錯誤的用戶名和密碼組合進行了嘗試,但仍然沒有錯誤並且程序運行完全正常。
public class emailfromgmail {
public static void main(String[]args)
{
final String from = "username";
final String pass = "password";
String to = "recipient@gmail.com";
String host="smtp.gmail.com";
String subject = "java Mail";
String body = "example of java mail api using gmail smtp";
//get the session object
Properties p = System.getProperties();
p.put("mail.smtp.starttls.enable","true");
p.put("mail.smtp.host",host);
p.put("mail.smtp.user",from);
p.put("mail.smtp.password",pass );
p.put("mail.smtp.port", "587");
p.put("mail.smtp.auth","true");
Session session = Session.getInstance(p,
new javax.mail.Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, pass);
}
});
try{
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
msg.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
msg.setSubject(subject);
msg.setText(body);
Transport.send(msg);
System.out.print("message sent successfully");
}
catch(MessagingException e){
e.printStackTrace();
}
}
}
我遇到了同樣的問題 - 我運行了我的程序並在不同的地方放入了一個對話框,看看它在哪里停止做任何事情。 我仍然不知道出了什么問題,但我嘗試了一種完全不同的方法並且它奏效了。 我沒有通過 TLS 發送,而是通過 SSL 發送。 我用過這個網站:
https://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/
他們的 TLS 不起作用 - 當我運行它時它沒有做任何事情。 他們的 SSL 就像一個魅力!
這是代碼:
package com.mkyong.common; import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class SendMailSSL { public static void main(String[] args) { Properties props = new Properties(); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.socketFactory.port", "465"); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.port", "465"); Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("username","password"); } }); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress("from@no-spam.com")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("to@no-spam.com")); message.setSubject("Testing Subject"); message.setText("Dear Mail Crawler," + "\\n\\n No spam to my email, please!"); Transport.send(message); System.out.println("Done"); } catch (MessagingException e) { throw new RuntimeException(e); } } }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.