java mail api setFrom不工作

时间:2012-10-07 10:51:06

标签: javamail

发送电子邮件:

public class SendMail {

public void sendEmail(final String from, final String password,String toAddress) {
    Properties props = new Properties();
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "465");
    Session session = Session.getDefaultInstance(props,
            new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(from,password);
                }
            });
    try
    {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse(toAddress));
        message.setSentDate(new Date());
        message.setSubject("Account Activation for T20home");
        message.setContent("Hello", "text/html");
        Transport transport = session.getTransport("smtp");
        transport.connect("smtp.gmail.com", from, password);
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
    }
    catch(MessagingException mex)
    {

    }
}
}

我可以发送这样的电子邮件:

SendMail send = new SendMail()
send.sendEmail("mailFrom1@gmail.com", "pass1","to1")

SendMail send1 = new SendMail()
send1.sendEmail("mailFrom2@gmail.com", "pass2","to1")

它运作良好,但是从mailFrom1@gmail.com发来两封信给“to1”发送电子邮件。

必须来自“mailFrom1@gmail.com”的一封信和“mailFrom2@gmail.com”中的一封信

setFrom无法正常工作

1 个答案:

答案 0 :(得分:0)

你已经制作了几个common mistakes described in the JavaMail FAQ(剪切和粘贴编程的危险)。一旦你修复它们,我怀疑你会遇到另一个问题,但让我们看看......