Java program to send email

Here is one simple example to send email from Java using gmail. Make sure that you added the java mail jars and change the from to address
 

Example

 
Add below dependency in your pom.xm
 
<dependency>
    <groupId>javax.mail</groupId>
    <artifactId>mail</artifactId>
    <version>1.4</version>
</dependency>
 
 

Create Java program to send email

Change email id and password accordingly.

package com.vinod.test;
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 SendEmail {
    public SendEmail() {
        SendMail("admin@gmail.com", "This is test message");
    }
    public void SendMail(String toAddress, String contentmessage) {
        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.googlemail.com");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class",
                "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "465");
        Session session = Session.getDefaultInstance(props,
                new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication("xxxxx@gmail.com",
                                "password");
                    }
                });
        try {
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("xxxxxxx@gmail.com"));
            message.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse(toAddress));
            message.setSubject("my email");
            message.setText(contentmessage);
            Transport.send(message);
            System.out.println("Email Done");
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }
    public static void main(String args[]) {
        new SendEmail();
    }
}

No comments:

Post a Comment

12 classic String-based Java interview questions with simple explanations and code.

  1️⃣ Check if a String is a Palindrome Problem Given a string, check if it reads the same forward and backward. Example: "madam...

Featured Posts