10.16. Sending Mail with SMTP
Problem
You need to send an email.
Solution
Use SMTPClient
from Commons Net. The following
example sends a simple email to somedude@aol.org
from tobrien@discursive.com
via the SMTP server
on host www.discursive.com
using port 25:
import org.apache.commons.net.smtp.SMTPClient; SMTPClient client = new SMTPClient( ); client.connect("www.discursive.com"); client.sendSimpleMessage("tobrien@discursive.com", "somedude@aol.com", "Hey! Call me when you get a chance." ); client.disconnect( );
This example sends a very simple email message to one recipient by
passing three arguments to client.sendSimpleMessage()
: the sender’s email
address, the recipient’s email address, and a
message. If you are trying to send a simple email message to multiple
recipients, pass a String[]
containing each
address as the second parameter to sendSimpleMessage( )
. The following example sends a simple email message to
multiple recipients by passing a String[]
to
sendSimpleMessage( )
:
import org.apache.commons.net.smtp.SMTPClient; SMTPClient client = new SMTPClient( ); client.connect("www.discursive.com"); String[] recipients = new String[2]; recipients[0] = "mission-control@nasa.gov"; recipients[1] = "announce@nasa.gov"; client.sendSimpleMessage("astronaut@nasa.gov", recipients, "The eagle has landed." ); client.disconnect( );
Discussion
Telnet to port 25 of
a SMTP server,
and
you will see the server respond with a numeric code (220).
SMTPReply.isPositiveCompletion( )
returns
true ...
Get Jakarta Commons Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.