Search code examples
javasmtpgmail-apismtpclientsmtp-auth

Save Session in SMTP protocol and JavaMail api


I develop a Java application that sends emails on behalf of the user.

To avoid saving the user's password, I want to store the Mail Session. However, I see that in Java's Mail api of the SMTP protocol, the implementation authenticate on each message sent!

Is it just an implementation or is it declared to be so in SMTP protocol?

My code:

I am using JavaMail API to start an SMTP Session and send an email, as follows:

//Set up headers
String from,to...

//Set up authentication
  Properties props = new Properties();  
   props.put("mail.smtp.host",host);  
   props.put("mail.smtp.auth", "true");  

  Session session = Session.getDefaultInstance(props,  
    new javax.mail.Authenticator() {  
      protected PasswordAuthentication getPasswordAuthentication() {  
    return new PasswordAuthentication(user,password);  
      }  
    });  

//Set up message
MimeMessage message = new MimeMessage(session); 
...

//Send message
  Transport.send(message);  

While in Transport.send(message) (Inside JavaMail api), there is the following implementation:

try{
  this.Connect()
  this.SendMessage(message)
  this.CloseConnection()
}

Can I use the implementation of transport.SendMessage(message) without transport.CloseConnection()? Thus I will save the session and continue using it.

Will SMTP support it? How much time the sessions will be kept?


Solution

  • Well it seems to work ok. Instead of using

    Transport.send(message);  
    

    Use:

    Transport transport = message.getTransport(address);
    try{
       transport.connect();
    }catch (Exception e){
       //already connected
    }
    transport.sendMessage(message);