Programming Tutorials

Sending Email from Java application (using gmail)

By: Narayanan in Java Tutorials on 2023-03-23  

This example uses Gmail SMTP server to send an email. Make sure to replace [email protected] and your_email_password with your actual email and password respectively. Also, replace [email protected] with the email address of the recipient.

import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;

public class SendEmail {
    
    public static void main(String[] args) {
        
        final String username = "[email protected]";
        final String password = "your_email_password";
        String recipient = "[email protected]";
        
        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.port", "587");
        
        Session session = Session.getInstance(props, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });
        
        try {
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(username));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient));
            message.setSubject("Subject of Email");
            message.setText("Body of Email");
            Transport.send(message);
            System.out.println("Email Sent");
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }
}





Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Java )

Latest Articles (in Java)