Java Email Send sendMail(String to, String from, String subject, String body, boolean bodyIsHTML)

Here you can find the source of sendMail(String to, String from, String subject, String body, boolean bodyIsHTML)

Description

send Mail

License

Open Source License

Declaration

public static void sendMail(String to, String from, String subject, String body, boolean bodyIsHTML)
            throws MessagingException 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

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

public class Main {
    public static void sendMail(String to, String from, String subject, String body, boolean bodyIsHTML)
            throws MessagingException {
        // 1 - get a mail session
        Properties props = new Properties();
        props.put("mail.transport.protocol", "smtps");
        props.put("mail.smtps.host", "smtp.gmail.com");
        props.put("mail.smtps.port", 465);
        props.put("mail.smtps.auth", "true");
        props.put("mail.smtps.quitwait", "false");
        Session session = Session.getDefaultInstance(props);
        session.setDebug(true);/*from   w  ww.j  av  a 2 s  . co m*/

        // 2 - create a message
        Message message = new MimeMessage(session);
        message.setSubject(subject);
        if (bodyIsHTML)
            message.setContent(body, "text/html");
        else
            message.setText(body);

        // 3 - address the message
        Address fromAddress = new InternetAddress(from);
        Address toAddress = new InternetAddress(to);
        message.setFrom(fromAddress);
        message.setRecipient(Message.RecipientType.TO, toAddress);

        // 4 - send the message
        Transport transport = session.getTransport();
        transport.connect("email@domin_name", "pass"); // OBS: set the email and pass for connection
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
    }
}

Related

  1. sendMail(Properties props, String recipients[], String subject, String message, String from)
  2. sendMail(Session session, Message message)
  3. sendMail(String filePathName, InternetAddress[] addresses, List> md5cellRows, String today, byte[] report1bytes, byte[] report2bytes, byte[] report3bytes)
  4. sendMail(String host, int port, String username, String password, String recipients, String subject, String content, String from)
  5. sendMail(String smtpServer, String to, String from, String subject, String body)
  6. sendMail(String toEmailId, String subject, String msgText, String from, String smtpServer, String userName, String password)
  7. sendMail(String vmName, String property, String emailId, boolean usageHigh)
  8. sendMessage(Message message)
  9. sendMessage(Message msg, Transport transport)