我正在尝试向上传文件的各个用户发送邮件。我有一个process.jsp页面,在该页面中,用户将输入邮件ID,当用户单击“发送”时,将在文件上传时发送邮件。我已经编写了用于发送邮件的代码,但它给出了类似[[发生错误:null的错误。文件已成功上传到MySQL数据库,但邮件未发送。
这是我的process.jsp页面<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>
这是我的EmailUtility.java页面注意:-我只需要两个字段,即一个文本字段用于邮件ID,另一个用于发送按钮。我不需要主题和内容字段
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);
}
}
这是我的SendMailAttachServlet.java文件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. */ }
<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>
现在servlet代码:
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. */ }
这是我的web.xml
文件:<?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>