How to Send Mail in Java?
What is JavaMail?
JavaMail is a Java API which allows you to compose, write and read emails. You can use this API to send and receive electronic mail through SMTP, POP3, and IMAP. The main advantage of JavaMail is the protocol-independent and platform-independent structure for sending and receiving emails.
You can use the below given JavaMail code in your mailing forms coding portion to send and receive mail.
JavaMail Coding:
package com.javapapers.java;
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 JavaEmail {
Properties emailProperties;
Session mailSession;
MimeMessage emailMessage;
public static void main(String args[]) throws AddressException,
MessagingException {
JavaEmail javaEmail = new JavaEmail();
javaEmail.setMailServerProperties();
javaEmail.createEmailMessage();
javaEmail.sendEmail();
}
public void setMailServerProperties() {
String emailPort = 587;//gmails 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 = { enter recipient mail id here };
String emailSubject = Java Email;
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;
String fromUser = your emailid here;//just the id alone without @gmail.com
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.);
}
}
Note: Replace the highlighted portion in the above code with recipient mail id, your mail id, and password accordingly.
How this faq is helpful: