Home > Projects > Simple Email
The sun.net.smtp.SmtpClient class provides a simple way to send basic emails, i.e., basic plain text messages, without the use of Java Mail or some other package. It should be noted that Sun does not recommend using the sun.* packages directly and it is possible that these classes might not be available in all versions of Java or from other vendors. Please read Sun's warning before using these classes. For most purposes, I recommend using the Commons Email package instead.
Example
Import the class.
import sun.net.smtp.SmtpClient;
Setup with server and to/from address.
SmtpClient smtp=new SmtpClient("my.mailserver.com");
smtp.from("me@mydomain.com");
smtp.to("someone@elsewhere.com");
Get stream and set fields.
PrintStream msg=smtp.startMessage();
msg.println("From: My Name<me@mydomain.com>");
msg.println("To: Someone Else<someone@elsewhere.com>");
msg.println("Subject: this is a test");
Put an empty line to start body of message.
msg.println("");
Write out message.
msg.println("This is the body of the email.");
Finish writing message to SMTP server.
smtp.closeServer(); msg.close();
Download
- SendMail.java: example program showing how to send a simple email.