简体   繁体   English

通过JAVA中的gmail smtp服务器发送电子邮件

[英]Sending Email via gmail smtp server in JAVA

What is the problem with this code? 这段代码有什么问题? Somehow it is getting in to an infinity loop at the line Transport.send(message); 它以某种方式进入了Transport.send(message);行的无限循环Transport.send(message); line, no error message, no exception, just maybe infinite loop (i don't know because i don't wait more than 5-10minute) 行,没有错误消息,没有异常,只是可能无限循环(我不知道因为我不等待超过5-10分钟)

final String username = "<mail_name>";
final String password = "<password>";

Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "465");

Session session = Session.getInstance(props,
        new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });

try {

    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress("<mail_from>@gmail.com"));
    message.setRecipients(Message.RecipientType.TO,
            InternetAddress.parse("<mail_to>@gmail.com"));
    message.setSubject("Test Subject");
    message.setText("Test");

    Transport.send(message);

    System.out.println("Done");

} catch (MessagingException e) {
    throw new RuntimeException(e);
}

Here I am giving some changes, that work fine for me: 在这里,我正在做一些改变,这对我来说很好:

Session session = Session.getInstance(props,null);

You instantiate message object as you did. 您像实例一样实例化消息对象。 And finally: 最后:

Transport transport = session.getTransport("smtp");
String mfrom = "yourGmailUsernameWithout@"// example laabidiraissi 
transport.connect("smtp.gmail.com", mfrom, "thepassword");
transport.sendMessage(message, message.getAllRecipients());

Edit, would you please give me a favor and copy/paste and try this example and show what it displays: 编辑,请你给我一个帮忙,复制/粘贴并尝试这个例子,并显示它显示的内容:

package com.test;

import java.util.Properties;

import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.junit.Test;

public class EmailService {

@Test
public void test(){
    Properties props = System.getProperties();
    props.put("mail.smtp.starttls.enable", true); // added this line
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.user", "username");
    props.put("mail.smtp.password", "password");
    props.put("mail.smtp.port", "587");
    props.put("mail.smtp.auth", true);



    Session session = Session.getInstance(props,null);
    MimeMessage message = new MimeMessage(session);

    System.out.println("Port: "+session.getProperty("mail.smtp.port"));

    // Create the email addresses involved
    try {
        InternetAddress from = new InternetAddress("username");
        message.setSubject("Yes we can");
        message.setFrom(from);
        message.addRecipients(Message.RecipientType.TO, InternetAddress.parse("receivermail"));

        // Create a multi-part to combine the parts
        Multipart multipart = new MimeMultipart("alternative");

        // Create your text message part
        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText("some text to send");

        // Add the text part to the multipart
        multipart.addBodyPart(messageBodyPart);

        // Create the html part
        messageBodyPart = new MimeBodyPart();
        String htmlMessage = "Our html text";
        messageBodyPart.setContent(htmlMessage, "text/html");


        // Add html part to multi part
        multipart.addBodyPart(messageBodyPart);

        // Associate multi-part with message
        message.setContent(multipart);

        // Send message
        Transport transport = session.getTransport("smtp");
        transport.connect("smtp.gmail.com", "username", "password");
        System.out.println("Transport: "+transport.toString());
        transport.sendMessage(message, message.getAllRecipients());


    } catch (AddressException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MessagingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
}

Ok. 好。 It is a little more complex than i tought for the first time... To summorize what i got: 这比我第一次尝试的要复杂一点......总结我得到的东西:

  • There is a very useful command: session.setDebug(true); 有一个非常有用的命令: session.setDebug(true); . If you set this true, every important process will be debuged to the console. 如果将此设置为true,则每个重要进程都将调到控制台。 I recommend to use it. 我建议使用它。
  • The second computer could only work with the secure option, you can switch this one with: Transport transport = session.getTransport("smtps"); 第二台计算机只能使用安全选项,您可以使用以下选项切换: Transport transport = session.getTransport("smtps"); rather of the non secure smtp... The JavaMail API Transport object will also take care of the ports (respectively smtp: 587, smtps: 465) 而不是非安全的smtp ... JavaMail API传输对象也将处理端口(分别为smtp:587,smtps:465)
  • You can use also the static method of the Transport class for sending the message and (saving it before, non static sendMessage method will not save the message), but this time you need to use the javax.mail.Authenticator at the session creation, like this: 您还可以使用Transport类的静态方法来发送消息和(以前保存它,非静态sendMessage方法不会保存消息),但这次您需要在创建会话时使用javax.mail.Authenticator,像这样:

     Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("login", "password"); } 

    }); });

1.4.2 JavaMailApi has another Exception than 1.4.7 version for this issue... 1.4.2 JavaMailApi对此问题有另一个异常而不是1.4.7版本......

If you don't use it, you can not authenticated with the static method. 如果不使用它,则无法使用静态方法进行身份验证。 If you use the instance method, you can. 如果使用实例方法,则可以。

  • One computer has maven and got the 1.4.2 version of the JavaMail API. 一台计算机有maven并获得了JavaMail API的1.4.2版本。 Second computer has a downloaded library, with version 1.4.7, which i guess also mess with the things 第二台计算机有一个下载的库,版本为1.4.7,我觉得这些东西也搞乱了
  • First comp Netbeans, second comp Intellij... +1) There are a lot of old, and bad example code at the internet, which makes harder to use this API properly. 第一个comp Netbeans,第二个comp Intellij ... +1)互联网上有很多旧的和坏的示例代码,这使得更难以正确使用这个API。

So pretty messed up, but there were some basic concept which should be focused... 所以非常混乱,但有一些基本概念应该集中......

I could reproduce the behaviour described in your question and fix it. 我可以重现你的问题中描述的行为并修复它。

The send method gets stuck at send方法陷入困境

SMTPTransport(Service).connect(String, int, String, String) line: 308   

The connection does not succeed because you have the wrong port for the gmail smtp host: 465 连接不成功,因为您的gmail smtp主机端口错误: 465

change it to 587 把它改成587

props.put("mail.smtp.port", "587");

and it will work. 它会起作用。

Using Simple Java Mail it should be straightforward: 使用Simple Java Mail应该很简单:

Email email = new Email();

email.setFromAddress("lollypop", "lol.pop@somemail.com");
email.addRecipient("C.Cane", "candycane@candyshop.org", RecipientType.TO);
email.setText("We should meet up!");
email.setTextHTML("<b>We should meet up!</b>");
email.setSubject("hey");

new Mailer("smtp.gmail.com", 25, "your user", "your password", TransportStrategy.SMTP_TLS).sendMail(email);
new Mailer("smtp.gmail.com", 587, "your user", "your password", TransportStrategy.SMTP_TLS).sendMail(email);
new Mailer("smtp.gmail.com", 465, "your user", "your password", TransportStrategy.SMTP_SSL).sendMail(email);

If you have two-factor login turned on, you need to generate an application specific password from your Google account. 如果您启用了双因素登录,则需要从Google帐户生成应用程序专用密码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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