Can I create a MimeMessage using one Session say session1 and send the mail using another Session session2?

John Zukowski

Sure.

import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;

public class MailExample {
  public static void main (String args[]) throws Exception {
    String host = args[0];
    String from = args[1];
    String to = args[2];
    String username = args[3];
    String password = args[4];

    // Get system properties
    Properties props = System.getProperties();

    // Setup mail server
    props.put("mail.smtp.host", host);

    // Get session
    Session session = Session.getInstance(props, null);

    // Define message
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(from));
    message.addRecipient(Message.RecipientType.TO, 
      new InternetAddress(to));
    message.setSubject("Hello JavaMail");
    message.setText("Welcome to JavaMail");

    Session session2 = Session.getInstance(props, null);

    // Send message
    Transport transport = session2.getTransport("smtp");
    transport.connect(host, username, password);
    transport.sendMessage(message, message.getAllRecipients());
    transport.close();
  }
}
0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact