Java Email
GMail SMTP
Yahoo Mail Integration
Hotmail Java Application
Email API Java

How can I send an email by Java application using GMail, Yahoo, or Hotmail?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

When developing a Java application, it's often necessary to include functionality for sending emails. This can be used for notifications, reports, or any other communication needs. JavaMail API is a standard library for sending and receiving emails within Java applications. In this article, we'll explore how to use JavaMail API to send emails through popular services like Gmail, Yahoo, or Hotmail (Outlook).

Prerequisites

Before we start, ensure you have the following:

  • JDK installed (Java Development Kit).
  • JavaMail API library.
  • Access credentials for Gmail, Yahoo, or Hotmail.

JavaMail API Setup

First, you need to download the JavaMail API and include it in your project. You can either add it manually to your classpath or use a dependency management tool like Maven or Gradle.

Maven Dependency

xml
1<dependency>
2    <groupId>javax.mail</groupId>
3    <artifactId>javax.mail-api</artifactId>
4    <version>1.6.2</version>
5</dependency>

Gradle Dependency

groovy
implementation 'javax.mail:javax.mail-api:1.6.2'

Sending an Email

The general process to send an email involves creating a session, constructing the email message, and sending it through a SMTP server.

General Steps

  1. Set up Properties: Configure the SMTP properties.
  2. Create a Session: Use the properties and authenticate with the email provider.
  3. Compose the Email: Define the message and its content.
  4. Send the Email: Use the Transport class to send the message.

Example Code

Here's an example of how you can send an email using JavaMail API through Gmail:

java
1import java.util.Properties;
2import javax.mail.*;
3import javax.mail.internet.*;
4
5public class EmailSender {
6
7    public static void main(String[] args) {
8        // Recipient's email ID needs to be mentioned.
9        String to = "[email protected]";
10
11        // Sender's email ID needs to be mentioned
12        String from = "[email protected]";
13        final String username = "[email protected]"; // your Gmail username
14        final String password = "your-password"; // your Gmail password
15
16        // Assuming you are sending email through smtp.gmail.com
17        String host = "smtp.gmail.com";
18
19        // Get system properties
20        Properties props = new Properties();
21
22        // Setup mail server
23        props.put("mail.smtp.auth", "true");
24        props.put("mail.smtp.starttls.enable", "true");
25        props.put("mail.smtp.host", host);
26        props.put("mail.smtp.port", "587");
27
28        // Get the Session object.
29        Session session = Session.getInstance(props,
30          new javax.mail.Authenticator() {
31            protected PasswordAuthentication getPasswordAuthentication() {
32                return new PasswordAuthentication(username, password);
33            }
34          });
35
36        try {
37            // Create a default MimeMessage object.
38            Message message = new MimeMessage(session);
39
40            // Set From: header field of the header.
41            message.setFrom(new InternetAddress(from));
42
43            // Set To: header field of the header.
44            message.setRecipients(Message.RecipientType.TO,
45                InternetAddress.parse(to));
46
47            // Set Subject: header field
48            message.setSubject("Subject Line");
49
50            // Now set the actual message
51            message.setText("Hello, this is a sample email.");
52
53            // Send message
54            Transport.send(message);
55
56            System.out.println("Sent message successfully....");
57
58        } catch (MessagingException e) {
59            throw new RuntimeException(e);
60        }
61    }
62}

Notes

  • Security: Gmail uses OAuth 2.0 for authentication. You should not use a raw password; instead, use AppPasswords or OAuth tokens.
  • Firewall and Less Secure Apps: Ensure that your Google Account allows less secure apps or set up a firewall exception. Note that "Less Secure Apps" should be avoided whenever possible due to security concerns.

Modifications for Yahoo and Hotmail

Yahoo

For Yahoo, the properties will slightly change:

properties
1mail.smtp.host = smtp.mail.yahoo.com
2mail.smtp.port = 587
3mail.smtp.auth = true
4mail.smtp.starttls.enable = true

Hotmail (Outlook)

For Hotmail, adjust the properties as follows:

properties
1mail.smtp.host = smtp-mail.outlook.com
2mail.smtp.port = 587
3mail.smtp.auth = true
4mail.smtp.starttls.enable = true

Summary

The table below summarizes the key configurations for each email provider:

ProviderSMTP HostSMTP PortTLS EnableAuth Required
Gmailsmtp.gmail.com587truetrue
Yahoosmtp.mail.yahoo.com587truetrue
Hotmailsmtp-mail.outlook.com587truetrue

Additional Topics

Handling Attachments

If you need to send attachments, use MimeBodyPart and Multipart to construct multi-part messages.

Exception Handling

Implement robust exception handling to catch and troubleshoot MessagingException and other potential issues.

Security Enhancements

Use OAuth 2.0 for a more secure method of authentication instead of email/password pairs.

By setting up the JavaMail API correctly, you can seamlessly integrate email functionality into your Java applications using Gmail, Yahoo, or Hotmail providers. This powerful API allows for a range of email-handling capabilities, making it ideal for enterprise and personal projects alike.


Course illustration
Course illustration

All Rights Reserved.