Servlets - Sending Email


To send an email utilizing your a Servlet is basic enough however to begin with you ought to have JavaMail API and Java Activation Framework (JAF) introduced on your machine.

Download and unfasten these records, in the recently made best dimension registries you will locate various container documents for both the applications. You have to include mail.jar and activation.jar records in your CLASSPATH.

Send a Simple Email

Here is a guide to send a straightforward email from your machine. Here it is accepted that your localhost is associated with the web and sufficiently competent to send an email. Same time ensure all the container records from Java Email API bundle and JAF bundle are accessible in CLASSPATH.

//File Name SendEmail.java


import java.io.*; 

import java.util.*; 

import javax.servlet.*; 

import javax.servlet.http.*; 

import javax.mail.*; 

import javax.mail.internet.*; 

import javax.activation.*; 

public class SendEmail extends HttpServlet { 

public void doGet(HttpServletRequest request, HttpServletResponse response) 

throws ServletException, IOException { 

//Recipient's email ID should be mentioned. 

String to = "abcd@gmail.com"; 

//Sender's email ID should be mentioned 

String from = "web@gmail.com"; 

//Assuming you are sending email from localhost 

String have = "localhost"; 

//Get framework properties 

Properties properties = System.getProperties();

//Setup mail server properties.setProperty("mail.smtp.host", host); //Get the default Session object. Session session = Session.getDefaultInstance(properties); //Set reaction content type response.setContentType("text/html"); PrintWriter out = response.getWriter(); try { //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.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); //Set Subject: header field message.setSubject("This is the Subject Line!"); //Now set the genuine message message.setText("This is real message"); //Send message Transport.send(message); String title = "Send Email"; String res = "Sent message successfully...."; String docType = "<!doctype html open \"-/w3c//dtd html 4.0 " + "transitional//en\">\n"; out.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" + "<body bgcolor = \"#f0f0f0\">\n" + "<h1 adjust = \"center\">" + title + "</h1>\n" + "<p adjust = \"center\">" + res + "</p>\n" + "</body> </html>" ); } catch (MessagingException mex) { mex.printStackTrace(); } } }

Now let us assemble the above servlet and make the accompanying sections in web.xml

.... 

<servlet> 

<servlet-name>SendEmail</servlet-name> 

<servlet-class>SendEmail</servlet-class> 

</servlet> 

<servlet-mapping> 

<servlet-name>SendEmail</servlet-name> 

<url-pattern>/SendEmail</url-pattern> 

</servlet-mapping> 

.... 

Now call this servlet utilizing URL http://localhost:8080/SendEmail which would send an email to given email ID abcd@gmail.com and would show following reaction −

Sent message successfully....

If you need to send an email to numerous beneficiaries at that point following strategies would be utilized to determine different email IDs −

void addRecipients(Message.RecipientType type, Address[] addresses) 

throws MessagingException

Here is the portrayal of the parameters −

  • type − This would be set TO, CC or BCC. Here CC speaks to Carbon Copy and BCC speaks to Black Carbon Copy. Precedent Message.RecipientType.TO

  • addresses − This is the variety of email ID. You would need to utilize InternetAddress() strategy while indicating email IDs.

Send a HTML Email

Here is a guide to send a HTML email from your machine. Here it is expected that your localhost is associated with the web and sufficiently skilled to send an email. In the meantime, ensure all the container documents from Java Email API bundle and JAF bundle are accessible in CLASSPATH.

This precedent is fundamentally the same as past one, aside from here we are utilizing setContent() technique to set substance whose second contention is "content/html" to indicate that the HTML content is incorporated into the message.

Using this model, you can send as large as HTML content you like.

//File Name SendEmail.java 

import java.io.*; 

import java.util.*; 

import javax.servlet.*; 

import javax.servlet.http.*; 

import javax.mail.*; 

import javax.mail.internet.*;
    
import javax.activation.*; 

public class SendEmail extends HttpServlet { 

public void doGet(HttpServletRequest request, HttpServletResponse response) 

throws ServletException, IOException { 

//Recipient's email ID should be mentioned. 

String to = "abcd@gmail.com"; 

//Sender's email ID should be mentioned 

String from = "web@gmail.com"; 

//Assuming you are sending email from localhost 

String have = "localhost"; 

//Get framework properties 

Properties properties = System.getProperties(); 

//Setup mail server 

properties.setProperty("mail.smtp.host", host); 

//Get the default Session object. 

Session session = Session.getDefaultInstance(properties);    
    //Set reaction content type 

response.setContentType("text/html"); 

PrintWriter out = response.getWriter(); 

try { 

//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.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); 

//Set Subject: header field 

message.setSubject("This is the Subject Line!"); 

//Send the real HTML message, as large as you like 

message.setContent("<h1>This is real message</h1>", "text/html" ); 

//Send message 

Transport.send(message); 

String title = "Send Email"; 

String res = "Sent message successfully...."; 

String docType = 

"<!doctype html open \"-/w3c//dtd html 4.0 " + "transitional//en\">\n"; 

out.println(docType + 

"<html>\n" + 

"<head><title>" + title + "</title></head>\n" + 

"<body bgcolor = \"#f0f0f0\">\n" + 

"<h1 adjust = \"center\">" + title + "</h1>\n" + 

"<p adjust = \"center\">" + res + "</p>\n" + 

"</body> 

</html>" 

);
   } catch (MessagingException mex) { 

mex.printStackTrace(); 

} 

} 

} 

Compile and run the above servlet to send HTML message on a given email ID.

Send Attachment in Email

Here is a guide to send an email with connection from your machine. Here it is expected that your localhost is associated with the web and sufficiently skilled to send an email.

//File Name SendEmail.java 

import java.io.*; 

import java.util.*; 

import javax.servlet.*; 

import javax.servlet.http.*; 

import javax.mail.*; 

import javax.mail.internet.*; 

import javax.activation.*; 

public class SendEmail extends HttpServlet { 

public void doGet(HttpServletRequest request, HttpServletResponse response) 

throws ServletException, IOException { 

//Recipient's email ID should be mentioned. 

String to = "abcd@gmail.com"; 

//Sender's email ID should be mentioned 

String from = "web@gmail.com"; 

//Assuming you are sending email from localhost 

String have = "localhost"; 

//Get framework properties 

Properties properties = System.getProperties(); 

//Setup mail server 

properties.setProperty("mail.smtp.host", host); 

//Get the default Session object. 

Session session = Session.getDefaultInstance(properties); 

//Set reaction content type 

response.setContentType("text/html"); 

PrintWriter out = response.getWriter();
    
     try { 

//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.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); 

//Set Subject: header field 

message.setSubject("This is the Subject Line!"); 

//Create the message part  

BodyPart messageBodyPart = new MimeBodyPart(); 

//Fill the message 

messageBodyPart.setText("This is message body"); 

//Create a multipar message 

Multipart multipart = new MimeMultipart(); 

//Set instant message part 

multipart.addBodyPart(messageBodyPart); 

//Part two is attachment 

messageBodyPart = new MimeBodyPart(); 

String filename = "file.txt"; 

DataSource source = new FileDataSource(filename); 

messageBodyPart.setDataHandler(new DataHandler(source)); 

messageBodyPart.setFileName(filename); 

multipart.addBodyPart(messageBodyPart); 

//Send the total message parts 

message.setContent(multipart ); 

//Send message 

Transport.send(message); 

String title = "Send Email"; 

String res = "Sent message successfully...."; 

String docType = 

"<!doctype html open \"-/w3c//dtd html 4.0 " + "transitional//en\">\n"; 

out.println(docType + 

"<html>\n" + 

"<head><title>" + title + "</title></head>\n" + 

"<body bgcolor = \"#f0f0f0\">\n" + 

"<h1 adjust = \"center\">" + title + "</h1>\n" + 

"<p adjust = \"center\">" + res + "</p>\n" + 

"</body> 

</html>" 

); 

} catch (MessagingException mex) { 

mex.printStackTrace(); 

} 

} 

} 

Compile and keep running above servlet to send a record as a connection alongside a message on a given email ID.

User Authentication Part

If it is required to give client ID and Password to the email server for validation reason then you can set these properties as pursues −

 props.setProperty("mail.user", "myuser"); 

props.setProperty("mail.password", "mypwd");

Rest of the email sending component would stay as clarified above.







© Javacodegeeks 2018 -
All Right Reserved and you agree to have read and accepted our term and condition.

Python 3