通过Javamail发送电子邮件

时间:2013-02-20 12:28:32

标签: java javamail

我一直在尝试使用javamail api发送电子邮件。来自smtp服务器(smtp.live.com)的调试显示550 5.3.4未采取请求的操作;要继续发送邮件,请登录您的帐户。

似乎创建了消息正常但不允许它发送。有什么想法吗?

  try
     {
     // Setup properties for e-mail server
     Properties props = System.getProperties();
     props.put("mail.smtp.host", mConfig.getEmailHost());
     props.put("mail.smtp.starttls.enable", "true");
     props.put("mail.smtp.auth", "true");
     props.put("mail.smtp.port", "587");

     // Get a Session object
     Session session = Session.getInstance(props, new MyAuthenticator());
     session.setDebug(true);
     Transport transport = session.getTransport("smtp");

     // Create message
     MimeMessage message = new MimeMessage(session);

     // Add the to/from fields
     message.setFrom(new InternetAddress(mFromAddr, mFromName));
     message.addRecipient(Message.RecipientType.TO, new InternetAddress(mToAddr));
     if (mCCAddrs != null)
        {
        for (int i=0; i<mCCAddrs.length; i++)
           message.addRecipient(Message.RecipientType.CC, new InternetAddress(mCCAddrs[i]));
        }
     // Add Subject
     message.setSubject(mEmailSubject);

     // Setup multipart message for including the attachment
     Multipart multipart = new MimeMultipart();

     // Create message body
     BodyPart messageBodyPart = new MimeBodyPart();
     messageBodyPart.setText(mEmailBody);
     multipart.addBodyPart(messageBodyPart);

     if (mAttachmentName != null)
        {
        // Create message attachment
        BodyPart messageAttachmentPart = new MimeBodyPart();
        messageAttachmentPart.setDataHandler(new DataHandler(new ByteArrayDatasource(data)));
        messageAttachmentPart.setFileName(mAttachmentName);
        multipart.addBodyPart(messageAttachmentPart);
        }

     // Send message
     message.setContent(multipart);
     transport.connect(mConfig.getEmailHost(), mConfig.getEmailUser(), mConfig.getEmailPassword());
     transport.sendMessage(message, message.getAllRecipients());
     transport.close();
     }
  catch (Exception ex)
     {
     ex.printStackTrace();
     throw new Exception("Failed to send e-mail: " + ex.getMessage());
     }
  `

2 个答案:

答案 0 :(得分:4)

您需要在身份验证器中实际包含一些凭据信息。服务器向您显示它不允许匿名发送电子邮件。

new MyAuthenticator()

       ^-------- fill this with some credentials

请注意,除非您的邮件服务器有一些特殊要求,否则使用standard password authenticator通常就足够了:


修改/更新

我根据您的反馈仔细查看了您的错误消息。在我看来,在使用Hotmail发送电子邮件之前,Hotmail要求您登录已设置的帐户并进行验证。在使用帐户之前,您可能希望使用Web浏览器登录并检查其中的激活链接。

答案 1 :(得分:1)

试用下面的代码。

    import java.util.Date;
    import java.util.Properties;
    import javax.mail.Address;
    import javax.mail.Message;
    import javax.mail.PasswordAuthentication;
    import javax.mail.Session;
    import javax.mail.Transport;
    import javax.mail.internet.AddressException;
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeMessage;

    public class TestJavaMail {
    private String SMTP_PORT = "465";
    private String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
    private String SMTP_HOST_NAME = "smtp.gmail.com";
    private String contentType = "text/html";
    private Properties smtpProperties;
    public TestJavaMail(){
    initProperties();
    }

    private void initProperties(){
    smtpProperties = new Properties();
    smtpProperties.put("mail.smtp.host", SMTP_HOST_NAME);
    smtpProperties.put("mail.smtp.auth", "true");
    smtpProperties.put("mail.debug", "true");
    smtpProperties.put("mail.smtp.port", SMTP_PORT);
    smtpProperties.put("mail.smtp.socketFactory.port",
    SMTP_PORT);
    smtpProperties.put ("mail.smtp.socketFactory.class",
    SSL_FACTORY);
    smtpProperties.put("mail.smtp.socketFactory.fallback",
    "false");
    }
    public static void main(String args[]) {
    String to= "sendToMailAddress";
    String from ="sender email_id";
    String pwd = "Sender password";
    String subject= "Java Mail";
    String body= "Testing to write Doc on java mail.";
    send(to, from, pwd , subject, body);
    }
    TestJavaMail.java Continued…
    public static void send(String to, final String from
    , final String pwd, String subject,String body){
    TestJavaMail tjm = new TestJavaMail();
    try
    {
    Properties props = tjm.getSmtpProperties() ;
    // -- Attaching to default Session, or we could start
    a new one --
    Session session = Session.getDefaultInstance(props,
    new javax.mail.Authenticator() {
    protected PasswordAuthentication
    getPasswordAuthentication() {
    return new PasswordAuthentication(from, pwd);
    }
    });
    // -- Create a new message --
    Message msg = new MimeMessage(session);
    // -- Set the FROM and TO fields --
    msg.setFrom(new InternetAddress(from));
    msg.setRecipients(Message.RecipientType.TO,
    InternetAddress.parse(to, false));
    // -- Set the subject and body text --
    msg.setSubject(subject);
    msg.setText(body);
    msg.setSentDate(new Date());
    // -- Send the message –
    Transport.send(msg);
    System.out.println("Message sent OK.");
    }
    catch (Exception ex)
    {
    ex.printStackTrace();
    }
    }
    public Properties getSmtpProperties() {
    return smtpProperties;
    }
    public void setSmtpProperties(Properties smtpProperties) {
    this.smtpProperties = smtpProperties;
    }
    }
    }

希望它会帮助你。