为什么此代码不能发送电子邮件?没有错误,它只是不发送。使用java应用程序发送电子邮件
package tips.mails;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Message.RecipientType;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendMail {
private String from;
private String to;
private String subject;
private String text;
public SendMail(String from, String to, String subject, String text){
this.from = from;
this.to = to;
this.subject = subject;
this.text = text;
}
public void send(){
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "465");
Session mailSession = Session.getDefaultInstance(props);
Message simpleMessage = new MimeMessage(mailSession);
InternetAddress fromAddress = null;
InternetAddress toAddress = null;
try {
fromAddress = new InternetAddress(from);
toAddress = new InternetAddress(to);
} catch (AddressException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
simpleMessage.setFrom(fromAddress);
simpleMessage.setRecipient(RecipientType.TO, toAddress);
simpleMessage.setSubject(subject);
simpleMessage.setText(text);
Transport.send(simpleMessage);
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String args[])
{
new SendMail("source", "dist","Subject", "Test Message!!!");
}
}
你有没有真正调用过send()? – David
如果没有例外,邮件服务器上会发生什么?你有没有调试过?把它指向你可以控制的邮件服务器(类似Smtp4Dev或类似的东西)并观察邮件服务器日志。也许服务器拒绝它?也许收件人将其标记为垃圾邮件?如果问题的本质是“我运行这个代码并且我的收件箱没有收到新消息”,那么有许多东西可能会出错,其中大部分与代码无关。 – David
什么是你的send()方法?..是不是要暗示??:P – PermGenError