JavaMail API Sending Your First Message
Tasks
------
Starting with the skeleton code, get the system Properties.
Add the name of your SMTP server to the properties for the mail.smtp.host key.
Get a Session object based on the Properties.
Create a MimeMessage from the session.
Set the from field of the message.
Set the to field of the message.
Set the subject of the message.
Set the content of the message.
Use a Transport to send the message.
Compile and run the program, passing your SMTP server, from address, and to address on the command line.
Check to make sure you received the message with your normal mail reader (Eudora, Outlook Express, pine, ...).
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
public class MailExample {
public static void main (String args[]) throws Exception {
String host = args[0];
String from = args[1];
String to = args[2];
// Get system properties
Properties props = System.getProperties();
// Setup mail server
props.put("mail.smtp.host", host);
// Get session
Session session = Session.getDefaultInstance(props, null);
// Define message
MimeMessage message = new MimeMessage(session);
// Set the from address
message.setFrom(new InternetAddress(from));
// Set the to address
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
// Set the subject
message.setSubject("Hello JavaMail");
// Set the content
message.setText("Welcome to JavaMail");
// Send message
Transport.send(message);
}
}
Demonstration
After executing the following command (replacing the email addresses and specifying your SMTP server):
java MailExample SMTP.Server from@address to@address
your program will send a mail message.
***************************************************************
No comments:
Post a Comment