Send email from java code.



This blog will explain how to send email from java code.

In order to send email from java code, we need to set properties of mail server and protocol. In my example I have set the authentication to false. So no authentication required before sending the email.

Below is the working java code to send email.


import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendEmail {
    public SendEmail() {
        super();
    }

    public static void main(String[] args) {
        SendEmail sendEmail = new SendEmail();
        //here you can set array size more to send mail to more users.
        String to[] = new String[1];
        to[0] = "kumar@gmail.com";

        sendEmail.sendEmail("dileep@gmail.com", to, "rongali@gmail.com", "Send Test Email from Java",
                            "Hello Email");
    }

    public void sendEmail(String from, String[] to, String bcc, String subject, String content) {
        try {
            // Get system properties
            Properties properties = System.getProperties();

            // Setup mail server
            //mail Server host
            properties.setProperty("mail.smtp.host", "smtp-relay.dileepkumarrongali.com");
            //mail server protocol
            properties.setProperty("mail.transport.protocol", "smtp");
            //authentication, I set as fase
            properties.setProperty("mail.smtp.auth", "false");

            // Get the default Session object.
            Session session = Session.getDefaultInstance(properties);

            InternetAddress[] addressTo = new InternetAddress[to.length];
            for (int i = 0; i < to.length; i++) {
                addressTo[i] = new InternetAddress(to[i]);
            }

            // Create a default MimeMessage object.
            MimeMessage message = new MimeMessage(session);

            // Set From: header field of the header.
            message.setFrom(new InternetAddress(from));

            // Set To: header field of the header.
            message.setRecipients(Message.RecipientType.TO, addressTo);

            //set bcc
            message.setRecipients(Message.RecipientType.BCC, bcc);

            // Set Subject: header field
            message.setSubject(subject);

            // Now set the actual message
            message.setText(content);

            // Send message
            Transport.send(message);
        } catch (MessagingException mex) {
            mex.printStackTrace();
        }

    }

}

Comments

Popular posts from this blog

BEA-000362 Server failed. Reason: [Management:141268]Parsing Failure in config.xml

Oracle OIM - Search and Update Organization using java API

Trim Leading and Trailing spaces from InputText on tab out.