如何在android中使用javamail发送gmail

时间:2014-10-31 11:39:59

标签: javamail

发送电子邮件时,我收到以下问题。

com.sun.mail.smtp.SMTPSendFailedException:530 5.7.0必须先发出STARTTLS命令。 z9sm9651423pdp.73 - gsmtp

我尝试使用以下代码发送邮件

public class SendMyMail {
private String from;
private String to;
private String subject;
private String text;

public SendMyMail(String from, String to, String subject, String text) {
    this.from = from;
    this.to = to;
    this.subject = subject;
    this.text = text;
}

// send method is called in the end
public boolean send() throws MessagingException {

    boolean sent = false;
    Properties props = new Properties();
    props.put("mail.transport.protocol", "gsmtps");
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.auth", "false");// set to false for no username
    props.put("mail.debug", "false");
    props.put("mail.smtp.port", "587");

    Session session = Session.getDefaultInstance(props);

    InternetAddress fromAddress = null;
    InternetAddress toAddress = null;
    Transport transport = session.getTransport("smtp");
    transport.connect();
    try {
        Message simpleMessage = new MimeMessage(session);
        fromAddress = new InternetAddress(from);
        toAddress = new InternetAddress(to);
        simpleMessage.setFrom(fromAddress);
        simpleMessage.setRecipient(RecipientType.TO, toAddress);
        simpleMessage.setSubject(subject);
        simpleMessage.setText(text);
        transport.sendMessage(simpleMessage,
                simpleMessage.getAllRecipients());
        sent = true;
    } catch (MessagingException e) {
        e.printStackTrace();
    } finally {
        transport.close();
    }
    return sent;
}

}

1 个答案:

答案 0 :(得分:0)

JavaMail FAQ has a simple example

如果您希望继续使用代码,请修复这些common mistakes,然后尝试将属性“mail.smtp.starttls.enable”设置为“true”。

请注意,没有“gsmtps”协议,因此您可以删除该设置。

当然,当您连接时 需要提供用户名和密码。