• Post Reply Bookmark Topic Watch Topic
  • New Topic

Servlets and java mail

 
david allen
Ranch Hand
Posts: 185
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

I am required to send mail from my servlet. I am also required to seek authorization with the smtp server before I can send mail. The code si below.

My question is should I perform this action once at start up and then store the variable Session session in the servlet context. I could then pass this variable to MyMail.java in its constructor. Is this a good idea or is it not thread safe?

I am not sure and any advice would be appreciated.

Thank you
David


Authenticator aAuth = new SMTPAuthenticator();

Properties aProp = System.getProperties();
aProp.setProperty("mail.smtp.host", "mail.yourdomain.com");
aProp.setProperty("mail.smtp.auth", "true");
Session session = Session.getInstance(aProp, aAuth);

private class SMTPAuthenticator extends javax.mail.Authenticator
{
protected PasswordAuthentication getPasswordAuthentication()
{
String username = "account@yourdomain.com";
String password = "some_pass";
return new PasswordAuthentication(username, password);
}
}
 
Ben Souther
Sheriff
Posts: 13411
Firefox Browser Redhat VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by david allen:
or is it not thread safe?


Are all requests going to use the same authorization?
If so, then thread safety isn't an issue. Authenticate once and use the same auth object (read-only) for all requests.

If different requests are going to need different auth parameters then, thread safety will be an issue.

In short anything stored as an instance variable or a context scoped param (session too) is not thread safe. If something is only set once, however and then accessed for reading only for the duration of the application's lifespan, then thread safety isn't really an issue.
 
david allen
Ranch Hand
Posts: 185
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes that is correct. All threads will use the same authorization instance. It will be read only.

Thank you for your reply.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!