繁体   English   中英

使用Java代码发送电子邮件

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM