使用gmail smtp host发送电子邮件时拒绝连接?

时间:2013-10-24 13:29:38

标签: java spring email

我有以下代码向我的gmail发送电子邮件。

public class Mainclass {

    public static void main(String args[]){


        String host = "smtp.gmail.com";
        String from = "from_address@fdsl.com";
        String to = "mymail@gmail.com";

        // Set properties
        Properties props = new Properties();
    props.put("mail.smtp.host", host);
    props.put("mail.debug", true);
    props.put("mail.smtp.auth", true);
    props.put("mail.smtp.starttls.enable", true);
    props.put("username", "mymail@gmail.com");
    props.put("password", "mypassword");

        // Get session
        Session session = Session.getInstance(props);

        try {
            // Instantiate a message
            Message msg = new MimeMessage(session);

            // Set the FROM message
            msg.setFrom(new InternetAddress(from));

            // The recipients can be more than one so we use an array but you can
            // use 'new InternetAddress(to)' for only one address.
            InternetAddress[] address = {new InternetAddress(to)};
            msg.setRecipients(Message.RecipientType.TO, address);

            // Set the message subject and date we sent it.
            msg.setSubject("Email from JavaMail test");
            msg.setSentDate(new Date());

            // Set message content
        msg.setText("This is the text for this simple demo using JavaMail.");

            // Send the message
            Transport.send(msg);

        }
        catch (MessagingException mex) {
            mex.printStackTrace();
        }

    }

}

但是当我运行代码时,我总是低于异常。

javax.mail.AuthenticationFailedException: failed to connect, no password specified?
    at javax.mail.Service.connect(Service.java:329)
    at javax.mail.Service.connect(Service.java:176)
    at javax.mail.Service.connect(Service.java:125)
    at javax.mail.Transport.send0(Transport.java:194)
    at javax.mail.Transport.send(Transport.java:124)
    at Mainclass.main(Mainclass.java:66)

我在这里遗漏了什么?我的密码是正确的。请帮帮我。

谢谢!

1 个答案:

答案 0 :(得分:0)

您是否正确设置了主机?另外,我没有看到您使用哪个端口进行连接。你设置了正确的端口吗? TLS是否是gmail的正确身份验证加密?

Please see the attached config:
   'SMTP::TLS',
    Host => 'smtp.gmail.com',
    Port => 587,
    User => 'username@gmail.com',
    Password => 'password'