[英]Sending email by using java code
早上好 。 我有個問題 。 我想使用eclipse oxygen通過Gmail發送電子郵件.2018年3月3日。 我使用了兩個jar:mail-1.4.7和激活1.1.1。 而且我允許我的Gmail帳戶的安全訪問權限降低。 這是我的代碼:
package Login_sys;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class EmailSend {
final String emailSMTPserver = "smtp.gmail.com";
final String emailServerPort = "587";
String receiverEmail = null;
String emailSubject = null;
String emailBody = null;
String from = null ;
String password = null ;
public EmailSend(String from,String password,String subject ,String message,String to)
{
this.from = from ;
this.password = password ;
this.emailSubject = subject ;
this.emailBody = message ;
this.receiverEmail = to ;
Properties props = System.getProperties();
props.put("mail.smtp.user", from);
props.put("mail.smtp.host", emailSMTPserver);
props.put("mail.smtp.port", emailServerPort);
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.password", password);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.socketFactory.port", emailServerPort);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
SecurityManager security = System.getSecurityManager();
try
{
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getInstance(props, auth);
Message msg = new MimeMessage(session);
msg.setText(emailBody);
msg.setSubject(emailSubject);
msg.setFrom(new InternetAddress(from));
msg.addRecipient(Message.RecipientType.TO,
new InternetAddress(receiverEmail));
Transport.send(msg);
System.out.println("send successfully");
} catch (Exception ex) {
System.err.println("Error occurred while sending.!");
}
}
private class SMTPAuthenticator extends javax.mail.Authenticator {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from , password);
}
}}
我從其他班級調用它:
EmailSend f = new EmailSend ("******@gmail.com","*****","Testing","testin
email","****@gmail.com");
它總是打印:發送時發生錯誤。 。 我不知道我的錯誤在哪里
您設置了錯誤的端口號。 更改為:
final String emailServerPort = "465";
Gmail SMTP端口(TLS):587
Gmail SMTP端口(SSL):465
要修復SSLHandshakeException
,您需要在JAVA_HOME/jre/lib/security
更新cacerts
。 獲取InstallCert.java
的副本。 在這里看看: InstallCert.java
您可以將jssecacerts
放在/lib/security
也可以使用KeyStore Explorer從jssecacerts
導出證書並將其導入cacerts
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.