package Controller;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendMail {
static String from = "******@gmail.com";
static String pass ="*****";
static String to = "****@gmail.com";
static String host = "smtp.gmail.com";
public static void main(String[] args) {
Properties properties = System.getProperties();
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.user", from);
properties.put("mail.smtp.password", pass);
properties.put("mail.smtp.port", "587");
properties.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(properties);
try{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
message.setSubject("This is the Subject Line!");
message.setText("Ithis is a test");
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
System.out.println("Sent message successfully....");
}
catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
此代码显示以下错误: javax.mail.MessagingException:无法将套接字转换为TLS; 任何人都可以帮助我,为什么不能将套接字转换为TLS。我该怎么做才能解决错误?请帮忙。
答案 0 :(得分:0)
默认情况下,Gmail不允许“安全性较低”的应用访问您的电子邮件。
为了让你的代码运行:
答案 1 :(得分:0)
文件cacerts
中尚未安装证书,或者您可能希望将google smtp网址设置为“受信任”。尝试添加此代码
properties.put("mail.smtp.ssl.trust", "smtp.gmail.com");
另一方面。当您尝试获取javax.mail.Authenticator
session
答案 2 :(得分:0)
//构建会话以创建MimeMessage以发送
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", "smtp.gmail.com");
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "587");
props.setProperty("mail.smtp.quitwait", "false");
Session session = Session.getDefaultInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("name_here", "password_here");
}
});