首页 > 解决方案 > 使用 java 代码发送电子邮件

问题描述

早上好 。我有个问题 。我想使用 eclipse oxygen.3 March 2018 通过 Gmail 发送电子邮件。我用了两个罐子:mail-1.4.7 和activation 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"); 

它总是打印:发送时发生错误。!. 我不知道我的错误在哪里

标签: javajargmail

解决方案


您设置了错误的端口号。将其更改为:

final String emailServerPort = "465";

Gmail SMTP 端口 (TLS):587

Gmail SMTP 端口 (SSL):465


推荐阅读