【发布时间】:2010-12-19 11:50:11
【问题描述】:
我必须通过 servlet 发送电子邮件,我尝试了很多代码,但它们都不能用于 gmail 帐户,有什么想法吗?
java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.auth", "true");
Authenticator auth = new SMTPAuthenticator();
//auth = null;
Session sess = Session.getInstance(props, auth);
sess.setDebug(false);
// -- Create a new message --
Message msg = new MimeMessage(sess);
// -- Set the FROM and TO fields --
msg.setFrom(new InternetAddress("myemail@gmail.com"));
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(
"sendtoemail", false));
msg.setSubject("Test");
msg.setText("Yippe");
msg.setSentDate(new Date());
Transport.send(msg);
public class SMTPAuthenticator extends javax.mail.Authenticator {
@Override
public PasswordAuthentication getPasswordAuthentication() {
String username = "myemail@gmail.com";
String password = "mypass";
return new PasswordAuthentication(username, password);
}
}
此代码抛出 javax.mail.MessagingException: Could not convert socket to TLS
异常
【问题讨论】: