The JavaMail API provides a platform-independent and protocol-independent framework to build mail and messaging applications. It contains a set of abstract classes by which a mail system can be designed having read, compose and send options.
Many protocols are supported by JavaMail API, such as
SMTP (Simple Mail Transfer Protocol) to deliver email.
POP (Post Office Protocol) to receive emails in one mailbox.
IMAP (Internet Message Access Protocol) to receive messages from multiple mailboxes for each user.
The following program shows, how to send an email using JavaMail API.
To test it, you may create a Java project using Eclipse IDE (if you are using it). Add the following jar files in the Java Build Path of the Eclipse project.
mailapi.jar and smtp.jar
package com.t4b.test;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class JavaMailTest {
Properties emailProperties;
Session mailSession;
MimeMessage emailMessage;
public static void main(String args[]) throws AddressException,
MessagingException {
JavaMailTest javaEmail = new JavaMailTest();
javaEmail.setMailServerProperties();
javaEmail.createEmailMessage();
javaEmail.sendEmail();
}
public void setMailServerProperties() {
String emailPort = "587";// gmail's smtp port
emailProperties = System.getProperties();
emailProperties.put("mail.smtp.port", emailPort);
emailProperties.put("mail.smtp.auth", "true");
emailProperties.put("mail.smtp.starttls.enable", "true");
}
public void createEmailMessage() throws AddressException,
MessagingException {
String[] toEmails = { "contact@tutorials4beginner.com" };
String emailSubject = "Java Email Subject";
String emailBody = "This is an email sent by JavaMail api.";
mailSession = Session.getDefaultInstance(emailProperties, null);
emailMessage = new MimeMessage(mailSession);
for (int i = 0; i < toEmails.length; i++) {
emailMessage.addRecipient(Message.RecipientType.TO,
new InternetAddress(toEmails[i]));
}
emailMessage.setSubject(emailSubject);
emailMessage.setContent(emailBody, "text/html");// for a html email
// emailMessage.setText(emailBody);// for a text email
}
public void sendEmail() throws AddressException, MessagingException {
String emailHost = "smtp.gmail.com";
// just the id alone without @gmail.com
String fromUser = "your emailid here";
String fromUserEmailPassword = "your email password here";
Transport transport = mailSession.getTransport("smtp");
transport.connect(emailHost, fromUser, fromUserEmailPassword);
transport.sendMessage(emailMessage, emailMessage.getAllRecipients());
transport.close();
System.out.println("Email sent successfully.");
}
}
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.