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

时间:2013-03-24 10:59:35

标签: java smtp javamail

此代码有什么问题?它以某种方式进入行Transport.send(message);行的无限循环,没有错误消息,没有异常,只是可能无限循环(我不知道因为我不等待超过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);
}

4 个答案:

答案 0 :(得分:19)

我在这里做了一些改动,对我来说很好:

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

您像实例一样实例化消息对象。最后:

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

编辑,请你给我一个帮忙并复制/粘贴并尝试这个例子并显示它显示的内容:

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();
    }
}
}

答案 1 :(得分:3)

确定。它比我第一次尝试的要复杂一点......总结我得到的东西:

  • 有一个非常有用的命令: session.setDebug(true); 。如果将此设置为true,则每个重要进程都将调到控制台。我建议使用它。
  • 第二台计算机只能使用安全选项,您可以使用以下代码切换:Transport transport = session.getTransport("smtps");而不是非安全smtp ... JavaMail API Transport对象也将处理端口(分别为smtp) :587,smtps:465)
  • 您也可以使用Transport类的静态方法来发送消息和(以前保存它,非静态sendMessage方法不会保存消息),但这次需要使用javax.mail。会话创建时的身份验证器,如下所示:

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

    });

1.4.2对于这个问题,JavaMailApi有另一个异常而不是1.4.7版本......

如果您不使用它,则无法使用静态方法进行身份验证。如果使用实例方法,则可以。

  • 一台计算机有maven并获得了1.4.2版本的JavaMail API。第二台计算机有一个下载的库,版本为1.4.7,我觉得这些东西也搞乱了
  • First comp Netbeans,second comp Intellij ... +1)互联网上有很多旧的和坏的示例代码,这使得使用此API变得更加困难。

非常混乱,但有一些基本概念应该集中......

答案 2 :(得分:1)

我可以重现您问题中描述的行为并进行修复。

send方法停留在

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

连接失败,因为gmail smtp主机端口错误:465

将其更改为587

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

它会起作用。

答案 3 :(得分:1)

使用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);

如果您启用了双因素登录,则需要从Google帐户生成application specific password