如何使用smtp服务器在动态地址电子邮件ID的java中发送电子邮件?

时间:2013-10-16 09:01:36

标签: java smtp

我使用以下代码发送电子邮件:

public static void main(String args[]) throws AddressException,    MessagingException
{
    SendMail javaEmail = new SendMail();
    javaEmail.setMailServerProperties();
    javaEmail.draftEmailMessage();
    javaEmail.sendEmail();
}

private void setMailServerProperties()
{
    Properties emailProperties = System.getProperties();
    emailProperties.put("mail.smtp.port", "586");
    emailProperties.put("mail.smtp.auth", "true");
    emailProperties.put("mail.smtp.starttls.enable", "true");
    mailSession = Session.getDefaultInstance(emailProperties, null);
}

private MimeMessage draftEmailMessage() throws AddressException, MessagingException
{
    String[] toEmails = { "aa@gmail.com" };
    String emailSubject = "Test email subject";
    String emailBody = "This is an email sent by http://www.howtodoinjava.com.";
    MimeMessage emailMessage = new MimeMessage(mailSession);
    /**
     * Set the mail recipients
     * */
    for (int i = 0; i < toEmails.length; i++)
    {
        emailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmails[i]));
    }
    emailMessage.setSubject(emailSubject);
    /**
     * If sending HTML mail
     * */
    emailMessage.setContent(emailBody, "text/html");
    /**
     * If sending only text mail
     * */
    //emailMessage.setText(emailBody);// for a text email
    return emailMessage;
}

private void sendEmail() throws AddressException, MessagingException
{
    /**
     * Sender's credentials
     * */
    String fromUser = "user-email@gmail.com";
    String fromUserEmailPassword = "*******";

    String emailHost = "smtp.gmail.com";
    Transport transport = mailSession.getTransport("smtp");
    transport.connect(emailHost, fromUser, fromUserEmailPassword);
    /**
     * Draft the message
     * */
    MimeMessage emailMessage = draftEmailMessage();
    /**
     * Send the mail
     * */
    transport.sendMessage(emailMessage, emailMessage.getAllRecipients());
    transport.close();
    System.out.println("Email sent successfully.");
}

}

我将java邮件jar文件添加到project.In这一行transport.connect(emailHost, fromUser, fromUserEmailPassword);我必须设置密码。

但我想要的是发送一封来自地址的电子邮件是动态的。这意味着用户可以设置他们的电子邮件地址,并将用户输入的电子邮件ID中的电子邮件发送到某个电子邮件ID。

1 个答案:

答案 0 :(得分:2)

您可以在MimeMessage上设置地址和发件人地址。它们不必相同。在draftEmailMessage方法中,添加以下内容:

emailMessage.setFrom(new InternetAddress(fromEmailAddress, fromName));
emailMessage.setSender(new InternetAddress(senderEmailAddress, senderName));

此处fromEmailAddress&amp; fromName是用户输入的地址和名称(名称是可选的)。

相应地,senderEmailAdresssenderName是发件人的地址和名称。