Issue
I am trying to send mail to respective user who upload file. I have one process.jsp page, in that user will enter mail id and when user click on send then mail will be sent as file is uploaded. I have written code for sending mail but it's giving error like There were an error: null. File is uploading into MySQL database successfully but mail is not sending.
This is my process.jsp page
<form action="SendMailAttachServlet" method="post" enctype="multipart/form-data">
<input type="email" name="mailid" value="" required="" size="60" placeholder="Please enter your mail address" />
<input type="submit" value="Send" />
<table>
<tr style="display:none">
<td>Subject </td>
<td><input type="text" name="subject" size="50" /></td>
</tr>
<tr style="display:none">
<td>Content </td>
<td><textarea rows="10" cols="39" name="content"></textarea> </td>
</tr>
</table>
</form>
Note:- I want only two fields i.e. one Textfield for mail id and another one for send button. I don't want Subject and Content fields
This is my EmailUtility.java page
package com.codejava.email;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class EmailUtility {
/**
* Sends an e-mail message from a SMTP host with a list of attached files.
*
*/
public static void sendEmailWithAttachment(String host, String port,
final String userName, final String password, String toAddress
)
throws AddressException, MessagingException {
// sets SMTP server properties
Properties properties = new Properties();
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", port);
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.user", userName);
properties.put("mail.password", password);
// creates a new session with an authenticator
Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
};
Session session = Session.getInstance(properties, auth);
// creates a new e-mail message
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(userName));
InternetAddress[] toAddresses = {
new InternetAddress(toAddress)
};
msg.setRecipients(Message.RecipientType.TO, toAddresses);
// msg.setSubject(subject);
msg.setSentDate(new Date());
// creates message part
MimeBodyPart messageBodyPart = new MimeBodyPart();
// messageBodyPart.setContent(message, "text/html");
// creates multi-part
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// sets the multi-part as e-mail's content
msg.setContent(multipart);
// sends the e-mail
Transport.send(msg);
}
}
This is my SendMailAttachServlet.java file
package com.codejava.email;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/SendMailAttachServlet")
@MultipartConfig(fileSizeThreshold = 1024 * 1024 * 2, // 2MB
maxFileSize = 1024 * 1024 * 10, // 10MB
maxRequestSize = 1024 * 1024 * 50) // 50MB
public class SendMailAttachServlet extends HttpServlet {
private String host;
private String port;
private String user;
private String pass;
public void init() {
// reads SMTP server setting from web.xml file
ServletContext context = getServletContext();
host = context.getInitParameter("host");
port = context.getInitParameter("port");
user = context.getInitParameter("user");
pass = context.getInitParameter("pass");
}
/**
* handles form submission
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// List<File> uploadedFiles = saveUploadedFiles(request);
String recipient = request.getParameter("recipient");
// String subject = request.getParameter("subject");
// String content = request.getParameter("content");
String resultMessage = "";
try {
EmailUtility.sendEmailWithAttachment(host, port, user, pass,
recipient);
resultMessage = "The e-mail was sent successfully";
} catch (Exception ex) {
ex.printStackTrace();
resultMessage = "There were an error: " + ex.getMessage();
} finally {
//deleteUploadFiles(uploadedFiles);
request.setAttribute("message", resultMessage);
getServletContext().getRequestDispatcher("/result.jsp").forward(
request, response);
}
}
/**
* Saves files uploaded from the client and return a list of these files
* which will be attached to the e-mail message.
*/
}
Solution
<form action="SendMailAttachServlet" method="post" enctype="multipart/form-data">
<input type="email" name="mailid" value="" required="" size="60" placeholder="Please enter your mail address" />
<input type="submit" value="Send" />
</form>
Now servlet code:
package com.codejava.email;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/SendMailAttachServlet")
@MultipartConfig(fileSizeThreshold = 1024 * 1024 * 2, // 2MB
maxFileSize = 1024 * 1024 * 10, // 10MB
maxRequestSize = 1024 * 1024 * 50) // 50MB
public class SendMailAttachServlet extends HttpServlet {
private String host;
private String port;
private String user;
private String pass;
public void init() {
// reads SMTP server setting from web.xml file
ServletContext context = getServletContext();
host = context.getInitParameter("host");
port = context.getInitParameter("port");
user = context.getInitParameter("user");
pass = context.getInitParameter("pass");
}
/**
* handles form submission
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// List<File> uploadedFiles = saveUploadedFiles(request);
String recipient = request.getParameter("mailid");//here you have to give the same name as your HTML name filed or input filed have
String resultMessage = "";
try {
EmailUtility.sendEmailWithAttachment(host, port, user, pass,
recipient);
resultMessage = "The e-mail was sent successfully";
} catch (Exception ex) {
ex.printStackTrace();
resultMessage = "There were an error: " + ex.getMessage();
} finally {
//deleteUploadFiles(uploadedFiles);
request.setAttribute("message", resultMessage);
getServletContext().getRequestDispatcher("/result.jsp").forward(
request, response);
}
}
/**
* Saves files uploaded from the client and return a list of these files
* which will be attached to the e-mail message.
*/
}
This is my web.xml
file:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
<display-name>EmailAttachWebApp</display-name>
<!-- SMTP settings -->
<context-param>
<param-name>host</param-name>
<param-value>smtp.gmail.com</param-value>
</context-param>
<context-param>
<param-name>port</param-name>
<param-value>465</param-value>
</context-param>
<context-param>
<param-name>user</param-name>
<param-value>[email protected]</param-value>
</context-param>
<context-param>
<param-name>pass</param-name>
<param-value>password</param-value>
</context-param>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
Answered By - abhinavxeon