Introduction to Java Sending Email
Java email sending is independent of the programming language on which we are working, such as Java, JavaEE, Python, and so on. Sending emails is one of the most basic requirements for transmission. It may be necessary to send signup or registration confirmations or error notices. The ability to send emails using Java program is provided, and it is extremely simple to send emails using Simple Java Mail. Also, a mailer object is created to send the email.
Key Takeaways
- The most prevalent and essential requirement for the majority of applications is the ability to send an email.
- Java offers Java Mail API, a framework for creating mail and messaging applications that are agnostic of platform and protocol.
- It is simple to send emails using Simple Java Mail.
- To begin, use EmailBuilder to generate an email object.
- Then, in order to send the email, you must create a mailer object using MailerBuilder and provide the email object to the mailer object.
What is Java Sending Email?
Java sending email is one of the most common solutions that also support TLS and SSL authentication is Jakarta Mail, or JavaMail as some still like to call it. It provides an API for sending and receiving emails over SMTP, POP3, as well as IMAP. It is integrated within the Jakarta EE platform and is agnostic of platforms and protocols. Jakarta Mail is another available add-on for the Java SE operating system.
How to Use Java Sending Email?
Three things are required in order to send emails using Java:
- API for JavaMail
- Activation Framework for Java (JAF)
- Details about your SMTP Server
The most recent versions of JavaMail API and JAF are available for download from the Java website. Extract them after you’ve downloaded these two successfully. To be able to send emails, include the mail.jar, smtp.jar, and activation.jar files in your classpath.
1. API for Java Mail
JavaMail API is a framework for creating Java client apps for mail and messaging that is agnostic of platform and protocol. It offers abstract classes comprising objects created in the email system as a generic interface for email programs.
Pros:
- It is well-organized and popular.
- It offers a variety of possibilities, including writing, reading, and sending emails.
- The Java Mail API can be used by other programs to facilitate the sending of mail confirmations or other communications.
Cons:
- Compiling codes could take a little longer.
- Utilizing the Mail API could use quite a lot of Java heap space.
2. Activation Framework for Java (JAF)
A common addition that Beans that operate with various external data types, such as media obtained from files and streams, might employ is the Java Activation Framework (JAF). It functions primarily as a generalized method for handling content and protocols for Java Beans.
3. Details about your SMTP Server
The mail client or application you use can set the address(es) of an SMTP email server, which often looks like this: smtp.serveraddress.com.
Setup Java Sending Email
Example:
Code:
package TestNG;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class NewTest
{
public static void main(String [] args)
{
String to = "[email protected]";
String from = "[email protected]";
String password = "xodbizaoiqijifre";
Properties props = new Properties();
props.setProperty("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
props.put("mail.debug", "true");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
Session sess = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from,password);
}
});
try {
Message msg = new MimeMessage(sess);
msg.setFrom(new InternetAddress(from));
msg.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
msg.setSubject("Demo Mail");
msg.setText("Welcome To My Domain ");
Transport.send(msg);
System.out.println("Your message is sent successfully");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
Output:
Call the getDefaultInstance() function to create a new session object and supply properties as an argument to retrieve all the necessary information, such as the hostname of the SMTP server. By passing the session object produced in the previous step, build a MimeMessage object.Sending emails using the javax.mail.Transport is the last step.
Sending an HTML E-mail Template
Emails can occasionally be sent using an HTML template, which means the email content is written in HTML. Because of this, the email has a professional layout and appealing appearance. The tool used to send emails using HTML templates is much the same as that used to send regular emails. The distinction is that we must use the setContent() method rather than the setText() method to define the email body, and we must specify “text/html” as the second argument in the setContent() function. Now let’s look at the application for sending emails with HTML templates:
I have used the above example with an additional HTML Template.
Code:
package TestNG;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class NewTest
{
public static void main(String [] args)
{
String to = "[email protected]";
String from = "[email protected]";
String password = "xodbizaoiqijifre";
Properties props = new Properties();
props.setProperty("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
props.put("mail.debug", "true");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
Session sess = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from,password);
}
});
try {
Message msg = new MimeMessage(sess);
msg.setFrom(new InternetAddress(from));
msg.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
msg.setSubject("HTML Format");
msg.setContent("<h1>This is a HTML text</h1>","text/html");
Transport.send(msg);
System.out.println("Your message is sent successfully");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
Output:
Java Email Formatting Text
Simply call the method setText(String)on the Message object to send an email in plain text using JavaMail. A standard technique for sending plain text emails from an SMTP server is implemented by the class PlainTextEmailSender, which is listed below. Information about the message and the SMTP server must be provided.
Host, port, user name (e-mail address), and password for the SMTP server.
Recipient address, subject, and message for emails.
Example:
Code:
package TestNG;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class NewTest
{
public static void main(String [] args)
{
String to = "[email protected]";
String from = "[email protected]";
String password = "xodbizaoiqijifre";
String message = "Send email using Plain text";
Properties props = new Properties();
props.setProperty("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
props.put("mail.debug", "true");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
Session sess = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from,password);
}
});
try {
Message msg = new MimeMessage(sess);
msg.setFrom(new InternetAddress(from));
msg.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
msg.setSubject("Plain Text Format");
msg.setContent(message,"text/html");
Transport.send(msg);
System.out.println("Your message is sent successfully");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
Output:
Multiple Java Sending Email
Emails sent to numerous recipients work the same way as emails sent to a single recipient. The distinction is that you must add additional recipients if you want to send an email to more than one recipient. The method below must be called in order to add multiple recipients, and we must pass the type of recipient and a list of email addresses as arguments:
We use an additional parse method to pass more than To email addresses.
Example:
Code:
package TestNG;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class NewTest
{
public static void main(String [] args)
{
String from = "[email protected]";
String password = "xodbizaoiqijifre";
String message = "Multiple Recipients on single email";
Properties props = new Properties();
props.setProperty("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
props.put("mail.debug", "true");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
Session sess = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from,password);
}
});
try {
Message msg = new MimeMessage(sess);
msg.setFrom(new InternetAddress(from));
msg.addRecipients(Message.RecipientType.TO,InternetAddress.parse("[email protected],[email protected]"));
msg.setSubject("Plain Text Format");
msg.setContent(message,"text/html");
Transport.send(msg);
System.out.println("Your message is sent successfully");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
Output:
Java Sending Email with an Attachment
Using the JavaMail API, you may send emails with attachments. We must build two MimeBodyPart objects, assign the text to one, and assign the datahandler to the other in order to send emails with attachments.
Example:
Code:
package TestNG;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class NewTest
{
public static void main(String [] args)
{
String from = "[email protected]";
String password = "xodbizaoiqijifre";
String message = "File attachment";
Properties props = new Properties();
props.setProperty("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
props.put("mail.debug", "true");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
Session sess = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from,password);
}
});
try {
Message msg = new MimeMessage(sess);
msg.setFrom(new InternetAddress(from));
msg.addRecipients(Message.RecipientType.TO,InternetAddress.parse("[email protected],[email protected]"));
msg.setSubject("Plain Text Format");
BodyPart attch1 = new MimeBodyPart();
attch1.setText("This is body of the mail");
BodyPart attch2 = new MimeBodyPart();
String filename = "D://articles1.txt";
DataSource source = new FileDataSource(filename);
attch2.setDataHandler(new DataHandler(source));
attch2.setFileName(filename);
Multipart finalattach = new MimeMultipart();
finalattach.addBodyPart(attch1);
finalattach.addBodyPart(attch2);
msg.setContent(finalattach);
Transport.send(msg);
System.out.println("Your message is sent successfully");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
Output:
New Session Object Creation:
- Make a MimeBodyPart object, then give text.
- A new MimeBodyPart object should be created and given a DataHandler object.
- The two MimeBodyPart objects should be created as MultiPart objects and assigned to this MultiPart object.
- Change the message on this MultiPart object.
- Method SetContent().
- To transmit the mail, utilize the Transport() method.
FAQs
Given below are the FAQs mentioned
Q1. What is java mail?
Answer:
The JavaMail API offers a foundation for developing mail and messaging applications that are agnostic of platforms and protocols.
Q2. How to send java email?
Answer:
- Using a JavaMail Session object, compose a message.
- Establish a MimeMessage object.
- Use the InternetAddress class to set the message sender and recipient.
- Use the setReplyTo() function to specify a “reply to” address.
- By using the MimeMessage object’s methods, determine the message’s contents.
Q3. What are the protocols used in Java mail API?
Answer:
Below are the protocols used in java mail API:
- SMTP
- IMAP
- MIME
- POP
- NNTP
Conclusion
A platform and protocol-neutral framework for creating mail and messaging applications is offered by the JavaMail API. A collection of abstract classes defining the elements of a mail system are made available by the JavaMail API. It is a standard extension (optional package) for reading, writing, and transmitting electronic messages.
Recommended Articles
This is a guide to Java Sending Email. Here we discuss the introduction, uses, setup, java email formatting text, and sending email with an attachment. You may also have a look at the following articles to learn more –