我想知道为什么以下基本的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();
}
}
}
答案 0 :(得分:0)
我遇到了同样的问题 - 我运行了我的程序并在各个地方放置了一个对话框,看看它停止了做什么。我仍然不知道出了什么问题,但我尝试了一种完全不同的方法而且它有效。我通过SSL发送,而不是通过TLS发送。我用过这个网站:
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);
}
}
}