Tuesday, September 9, 2008

JavaMail SMTP Authentication

There are a couple ways to authenticate yourself when using JavaMail APIs to send e-mail through an SMTP server.

Here's one way:


public void sendMail(String fromAddress,
String recipients,
String subject,
String content,
String contentType,
String smtpHost,
int smtpPort,
String username,
String password) {
try {

Properties props = System.getProperties();
Session session = Session.getDefaltInstance(props,null);

MimeMessage message = new MimeMessage(session);

message.setFrom(fromAddress);
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients, false));

message.setSubject(subject);
message.setContent(content,contentType);
message.setSentDate(new Date());

Transport transport = session.getTransport("smtp");
transport.connect(smtphost,smtpPort,username,password);
transport.sendMessage(message,message.getAllRecipients());
transport.close();

} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}


I don't like that way, because it's no good for anything but sending via an SMTP server with password based authentication. So, if I want to send e-mail through an SMTP server that has, say, a white-listed IP policy so I don't need to provide authentication, I have to write a whole new function that will duplicate a significant part of that code. Also, that long list of arguments to the function is just ugly, but it's what you're stuck with if you abstract a function that's hard-coded for SMTP password authentication.

Here's a better way, that is abstracted nicely:

public void sendMail(Properties props,
Authenticator authenticator,
String fromAddress,
String recipients,
String subject,
String content,
String contentType) {
try {

Session session = Session.getDefaultInstance(props, authenticator);

Message message = new MimeMessage(session);

message.setFrom(fromAddress);
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients, false));

message.setSubject(subject);
message.setContent(content,contentType);
message.setSentDate(new Date());

Transport.send(message);

} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}


The function above can be used to send e-mail with all sorts of configurations. All you have to do is pass it the Properties and, if you need to, an instance of a class extending javax.mail.Authenticator. Here's an example to send an e-mail identical to the first example above:

Properties props = System.getProperties();
props.put("mail.smtp.host","smtpHost");
props.put("mail.smtp.port","smtpPort");
props.put("mail.smtp.auth","true");

Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username","password");
}
};

sendMail(props,auth,"no-reply@mysite.com","user@site.com","Hello World","Wow, big world.","text/plain");


And, to send an e-mail without authentication (as in the IP white-list policy):

Properties props = System.getProperties();
props.put("mail.smtp.host","smtpHost");
props.put("mail.smtp.port","smtpPort");

sendMail(props,null,"no-reply@mysite.com","user@site.com","Hello World","Wow, big world.","text/plain");


The great part is that the function sending the e-mail doesn't need to know anything about how it's going to do it, since the configuration is entirely passed in as arguments via the session and the optional authenticator. There is, however, a catch that I've noticed has tripped people up all over the internet. The values you set to your Properties object must all be of class String. For example, this works

Properties props = System.getProperties();
props.put("mail.smtp.host","mail.mysite.com");
props.put("mail.smtp.port","587");
props.put("mail.smtp.auth","true");

Whereas, this does not:

Properties props = System.getProperties();
props.put("mail.smtp.host","mail.mysite.com");
props.put("mail.smtp.port",587);
props.put("mail.smtp.auth",true);

It doesn't matter that the values for mail.smtp.port and mail.smtp.auth are an int and a boolean, respectively. If they are not specified as a String, Transport.sendMessage(message) will fail.

* As a disclaimer, I typed the above code, rather than copy and paste from a program I've compiled, so I apologize if there's a typo anywhere up there that prevents it from compiling.

35 comments:

Bill Shannon said...

FYI, JavaMail 1.4.2 was enhanced to handle properties that aren't Strings.

Anonymous said...

I know you posted this a few years ago, but just wanted to drop a line to say I like your implementation, and I'm using it myself. It's clean, logical, and simple. Thanks!

Anonymous said...

Wow...there are more valuable information in this site. we can learn more from this site. Thanks for share toko online

voyance directe said...

Thanks a lot for sharing such a wonderful post, it is a very nice site i really enjoyed to visit this site.

Anonymous said...

Nice post, I am very happy to be here because this is a very good site that provides lots of information. Keep Blogging :D penghilang jerawat murah

Rental mobil murah solo said...

Very nice post. I just stumbled upon your weblog and wished to say that I have truly enjoyed browsing your weblog posts.

Anonymous said...

A good example of content presentation. Thanks for sharing this information. visit here

Anonymous said...

I love your site, This is a very impressive articles. keep posting pusatparcel.com :)

duo berry murah said...

This is a great inspiring article.I am pretty much pleased with your good work. duo berry

Anonymous said...

This is exactly what I was looking for. Thanks for sharing this great article! That is very interesting Smile I love reading and I am always searching for informative information like this! Visit Here

Anonymous said...

A very interesting read and a great post alltogether. thanks for sharing this information. printer id card

karangan bunga bengkulu said...

I do wish there were more people like you around on the interwebs. Not many people are careful with their words, including myself sometimes. Thanks

Mebel Jepara said...

This is a great article, Thanks for giving me this information. Keep posting
Mebel Jepara Murah :
Mebel Jepara Online :
Kursi Tamu :
Mebel Jepara Minimalis :
Mebel Jepara Online :
Mebel Jepara :
Mebel Jati :
Mebel Jati Jepara :
Kursi Tamu Jati :
Furniture Jati :
Karya Priboemi Jepara :
Kursi Tamu Jati :
Furniture jepara Online :
Mebel jepara
Mebel Jati
Mebel Jepara :
Mebel Jepara Murah
Mebel Minimalis
Meja Makan Minimalis :
Kursi Tamu Mewah
gebyok jepara
Meja Makan
Tempat Tidur Jati

Anonymous said...

I was waiting for this type article and I have gained some useful information from this site. Thanks for sharing this information. Keep blogging. florist bali

toko bunga pekalongan said...

This is a great inspiring article.I am pretty much pleased with your good work.You put really very helpful information. Thanks for sharing

Anonymous said...

You're Awesome. Enjoyed every bit of your article post. Really looking forward to read more. Really Cool. visit here

Anonymous said...

Thank's for taking the time to publish this information very useful! I've been looking for books of this nature for a way too long. I'm just glad that I found yours. Looking forward for your next post. :) filter air reverse osmosis

Printer ID Card said...

That was a great JavaMail. I Love it

Regards,
Printer Kartu | Printer ID Card | Cetak ID Card

jual furniture said...

kamar tidur anak
kamar tidur
kamar tidur minimalis
kursi makan
kitchen set
sofa tamu
gazebo
table tv

dipan klasik
kursi pantai
kursi louis
kaligrafi
dipan rococo
kursi rococo
kursi sudut
kursi tamu minimalis

sofa klasik
set kursi makan
meja rias
meja kantor
meja belajar
lemari pakaian
lemari buku
box bayi

Anonymous said...

Hi, This is a great post, it was very informative. I look forward in reading more of your work. visit here Thank you

Anonymous said...

Hi, This is a great post, it was very informative. I look forward in reading more of your work. Thank you

pengolahan air bersih said...

Thank's for taking the time to publish this information very useful! I've been looking for books of this nature for a way too long. I'm just glad that I found yours. Looking forward for your next post. :)

bunga papan bandung said...

I am happy to find this post very useful for me, very entertaining and informative.

toko bunga di jakarta said...

Great info. I love all the posts, I really enjoyed, I would like more information about this, thank you

virgin coconut oil supplier said...

Wonderful webiste, I love reading your post. I will bookmark it and I am looking forward to reading new articles.

xjd7410@gmail.com said...

polo ralph lauren
true religion outlet
burberry outlet
nfl jerseys wholesale
kobe bryant shoes
coach factory outlet
kobe 10 shoes
vans shoes sale
true religion jeans sale
instyler max
oakley sunglasses
gucci belts
michael kors outlet clearance
louis vuitton outlet
jordan 11 concord
coach outlet online
toms outlet
toms shoes
jordan 3 white cenment
kevin durant shoes 7
jordan retro
polo outlet
gucci outlet
cheap air jordans
jordan 4 toro
coach outlet
ray ban sunglasses
jordan 3
gucci handbags
chenyingying20160806

PT Tirtapure Envirotek said...

PT Tirtapure Envirotek adalah perusahaan nasional yang berkiprah dalam industri pengolahan air bersih dan air limbah sebagai kontraktor dan penyedia peralatan
FRP Filter Tank
Pressure Filter Tank
Water Pressure Tank
Membrane Pressure Tank
Panel Water Tank
Clarifier Tank
Membrane Reverse Osmosis
Membrane Housing
Cartridge Filter
Cartridge Filter Housing
Filter Bag
Bag Filter Housing
Ultraviolet Sterilizer
Dosing Pump
Ozone Generator
Pasir Silika
Karbon Aktif
Manganese Greensand Plus
Ion Exchange Resin
Reverse Osmosis System
Water Demineralization System
Water Softener System
WWTP Biofilter System

爸爸 x said...

20170803 junda
mizuno shoes
coach outlet clearance
coach outlet store online
kd shoes
ralph lauren
oakley sunglasses wholesale
cheap oakley sunglasses
michael kors outlet clearance
camisetas futbol baratas
herve leger dresses

Anonymous said...

Great...working like charm

http://tokobungawastukencana.com

Anonymous said...

Thanks for share

toko bunga wastukencana bandung

Bunga papan bandung said...

Nice posting

Toko bunga di palasari bandung said...

Nice posting

Pervez Joarder said...

At this time, I’m thus quite satisfied you should thought we would discover with this problematic topic nowadays. This has with certainty completely ready awesome few moments. Rather have necessary a few possibilities with this topic and therefore that you have exhibited many people thus. Already go along with right Cash Advance Regards rather a lot!

Cara Mengatasi Cacar Air said...

This information is very useful. thank you for sharing. and I will also share information about health through the website

Obat gatal Kudis/gudik
Walatra Gamat Emas Kapsul
Vitamin Untuk Kesehatan Anak
Penyebab sering mimisan
Cara Mengatasi Cacar Air
Cara Menghilangkan Kantung mata
Obat Telinga Berkerak dan Berair

Alex daina said...

Numerous shipper loan moneylenders publicize that the cash will be accessible in as quick as 10 days, and dissimilar to a bank advance that have a settled financing cost. Cash Advances Chicago