简体   繁体   English

通过Javamail发送电子邮件

[英]Sending Email through Javamail

I've been trying to send an email using the javamail api. 我一直在尝试使用javamail api发送电子邮件。 The debugs from the smtp server (smtp.live.com) are showing 550 5.3.4 Requested action not taken; 来自smtp服务器(smtp.live.com)的调试显示550 5.3.4未执行请求的操作; To continue sending messages, please sign in to your account. 要继续发送消息,请登录到您的帐户。

It seems to create the message fine but doesn't allow it to send. 似乎可以很好地创建消息,但不允许发送。 Any ideas why? 有什么想法吗?

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

You need to actually include some credential information in your authenticator. 您实际上需要在身份验证器中包括一些凭据信息。 The server is indicating to you that it doesn't allow sending emails anonymously. 服务器正在向您指示它不允许匿名发送电子邮件。

new MyAuthenticator()

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

Note that, unless your mail server has some special requirements, that it is normally sufficient to use the standard password authenticator : 请注意,除非您的邮件服务器有一些特殊要求,否则通常使用标准密码身份验证器就足够了:


Edit/Update 编辑/更新

I took a closer look at your error message, based on your feedback. 根据您的反馈,我仔细查看了您的错误消息。 It looks to me like Hotmail is requiring you to login to the account you have setup and verify it, before using it to send emails. 在我看来,Hotmail要求您先登录已设置的帐户并进行验证,然后再使用该帐户发送电子邮件。 You may want to login using a web browser and checking for an activation link from them, prior to using the account. 在使用该帐户之前,您可能需要使用Web浏览器登录并从中检查激活链接。

Try out the Below Code. 试用以下代码。

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

Hope it Will Help you. 希望对您有帮助。

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

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