Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap
irt.Org
#

Q4087 How to send SMTP mail from a servlet?

You are here: irt.org | FAQ | Java | Q4087 [ previous next ]

How to send SMTP mail from a Servlet. Requires a Mail Host ID and IP, but once you have that you can spam the world or send classy business mails to your hearts content. We send 100+ alert mails a day using this snippet of code and have yet to experience issues....

// these are required, plus any other imports you need
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.mail.*;
import javax.mail.internet.*;

/**
  * this is not a complete application. The mail elements that are
  * specified are all that is required to send mail. You may need to
  * surround this snippet with more code to make it work for you.
  */
public class mailUtils extends Object {

  public static String sendMails() {
    
    ////////////////////////////////////////////////////////////////////
    // requires a valid mail host ID and IP
    // 
    boolean isHTML = true; // set to false for Plain Text mail
    Properties props = new Properties();
    // insert your Mail Host ID and IP
    props.put("mail.smtp.host","0.0.0.0");
    
    // create properties and get the Session
    Session session = Session.getDefaultInstance(props, null);
    
    try {
      // command to create a message
      Message msg = new MimeMessage(session);
    
      // set the message type
      if (isHTML) {
        msg.setContent(msgText, "text/html");
      } else {
        msg.setContent(msgText, "text/plain"); 
      }
    
      // set the from address NOTE: include <> around email address
      InternetAddress FROM = new InternetAddress("Name or ID <email@address.com>");
      msg.setFrom(FROM);
    
      // set the TO addresses
      InternetAddress[] addressto = {new InternetAddress("to@email.com")};
      msg.setRecipients(Message.RecipientType.TO, addressto);

      // set the CC addresses
      InternetAddress[] addresscc = {new InternetAddress("cc@email.com")};
      msg.setRecipients(Message.RecipientType.CC, addresscc);

      // set the BCC addresses
      InternetAddress[] addressbcc = {new InternetAddress("bcc@email.com")};
      msg.setRecipients(Message.RecipientType.BCC, addressbcc);
    
      // set the subject
      msg.setSubject("Subject line text");
    
      // send the message
      Transport.send(msg);
    
    } catch (MessagingException mex) {
      // messaging exceptions
      returnText = "MessageError:" + mex;
      return returnText;
      
    } catch (Exception e) {
      // other exceptions
      returnText = "Error:" + e;
      return returnText;
      
    }
  }
}

Submitted by mechanismo

©2018 Martin Webb