今天讲述java组件JavaMail实现邮件的发送功能
应用一下百度百科上面JavaMail的描述
=================================================================
package entity;
import java.util.Vector;
public class Email {
private String mailTo = null;
private String mailFrom = null;
private String smtpHost = null;
private String messageBasePath = "";
private String subject;
private String msgContent;
private Vector attachedFileList;
private String mailAccount = null;
private String mailPass = null;
private String messageContentMimeType = "text/html; charset=gb2312";
private String mailbccTo = null;
private String mailccTo = null;
public String getMailTo() {
return mailTo;
}
public void setMailTo(String mailTo) {
this.mailTo = mailTo;
}
public String getMailFrom() {
return mailFrom;
}
public void setMailFrom(String mailFrom) {
this.mailFrom = mailFrom;
}
public String getSmtpHost() {
return smtpHost;
}
public void setSmtpHost(String smtpHost) {
this.smtpHost = smtpHost;
}
public String getMessageBasePath() {
return messageBasePath;
}
public void setMessageBasePath(String messageBasePath) {
this.messageBasePath = messageBasePath;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getMsgContent() {
return msgContent;
}
public void setMsgContent(String msgContent) {
this.msgContent = msgContent;
}
public Vector getAttachedFileList() {
return attachedFileList;
}
public void setAttachedFileList(Vector attachedFileList) {
this.attachedFileList = attachedFileList;
}
public String getMailAccount() {
return mailAccount;
}
public void setMailAccount(String mailAccount) {
this.mailAccount = mailAccount;
}
public String getMailPass() {
return mailPass;
}
public void setMailPass(String mailPass) {
this.mailPass = mailPass;
}
public String getMessageContentMimeType() {
return messageContentMimeType;
}
public void setMessageContentMimeType(String messageContentMimeType) {
this.messageContentMimeType = messageContentMimeType;
}
public String getMailbccTo() {
return mailbccTo;
}
public void setMailbccTo(String mailbccTo) {
this.mailbccTo = mailbccTo;
}
public String getMailccTo() {
return mailccTo;
}
public void setMailccTo(String mailccTo) {
this.mailccTo = mailccTo;
}
public Email(){}
}
package bean;
import java.io.IOException;
import java.util.Date;
import java.util.Enumeration;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.AuthenticationFailedException;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import mail.MailAuthenticator;
import entity.Email;
public class EmailBean {
private Email email;
// 是否采用调试方式
private boolean debug = false;
public Email getEmail() {
return email;
}
public void setEmail(Email email) {
this.email = email;
}
public EmailBean(){}
public EmailBean(Email email)
{
this.email=email;
}
private void fillEmail(Session session, MimeMessage msg) throws IOException,
MessagingException {
String fileName = null;
Multipart mPart = new MimeMultipart();
if (email.getMailFrom() != null) {
msg.setFrom(new InternetAddress(email.getMailFrom()));
System.out.println("发送人Mail地址:" + email.getMailFrom());
} else {
System.out.println("没有指定发送人邮件地址!");
return;
}
if (email.getMailTo() != null) {
InternetAddress[] address = InternetAddress.parse(email.getMailTo());
msg.setRecipients(Message.RecipientType.TO, address);
System.out.println("收件人Mail地址:" + email.getMailTo());
} else {
System.out.println("没有指定收件人邮件地址!");
return;
}
if (email.getMailccTo() != null) {
InternetAddress[] ccaddress = InternetAddress.parse(email.getMailccTo());
System.out.println("CCMail地址:" + email.getMailccTo());
msg.setRecipients(Message.RecipientType.CC, ccaddress);
}
if (email.getMailbccTo() != null) {
InternetAddress[] bccaddress = InternetAddress.parse(email.getMailbccTo());
System.out.println("BCCMail地址:" + email.getMailbccTo());
msg.setRecipients(Message.RecipientType.BCC, bccaddress);
}
msg.setSubject(email.getSubject());
InternetAddress[] replyAddress = { new InternetAddress(email.getMailFrom()) };
msg.setReplyTo(replyAddress);
// create and fill the first message part
MimeBodyPart mBodyContent = new MimeBodyPart();
if (email.getMsgContent() != null)
mBodyContent.setContent(email.getMsgContent(), email.getMessageContentMimeType());
else
mBodyContent.setContent("", email.getMessageContentMimeType());
mPart.addBodyPart(mBodyContent);
// attach the file to the message
if (email.getAttachedFileList() != null) {
for (Enumeration fileList = email.getAttachedFileList().elements(); fileList
.hasMoreElements();) {
fileName = (String) fileList.nextElement();
MimeBodyPart mBodyPart = new MimeBodyPart();
// attach the file to the message
FileDataSource fds = new FileDataSource(email.getMessageBasePath()
+ fileName);
System.out.println("Mail发送的附件为:" + email.getMessageBasePath() + fileName);
mBodyPart.setDataHandler(new DataHandler(fds));
mBodyPart.setFileName(fileName);
mPart.addBodyPart(mBodyPart);
}
}
msg.setContent(mPart);
msg.setSentDate(new Date());
}
public String sendEmail() throws IOException, MessagingException {
Properties props = System.getProperties();
props.put("mail.smtp.host", email.getSmtpHost());
props.put("mail.smtp.auth", "true");
props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.port", "465");
props.setProperty("mail.smtp.socketFactory.port", "465");
MailAuthenticator auth = new MailAuthenticator();
Session session = Session.getInstance(props, auth);
session.setDebug(debug);
MimeMessage msg = new MimeMessage(session);
Transport trans = null;
String result="";
try {
fillEmail(session, msg);
// send the message
trans = session.getTransport("smtp");
try {
trans.connect(email.getSmtpHost(), MailAuthenticator.MAIL_USER,
MailAuthenticator.MAIL_PASSWORD);
} catch (AuthenticationFailedException e) {
e.printStackTrace();
result = "连接邮件服务器错误";
return result;
} catch (MessagingException e) {
result = "连接邮件服务器错误";
return result;
}
Transport.send(msg);
trans.close();
} catch (MessagingException mex) {
result = "发送邮件失败";
mex.printStackTrace();
Exception ex = null;
if ((ex = mex.getNextException()) != null) {
System.out.println(ex.toString());
ex.printStackTrace();
}
return result;
} finally {
try {
if (trans != null && trans.isConnected())
trans.close();
} catch (Exception e) {
System.out.println(e.toString());
}
}
System.out.println("发送邮件成功!");
return "";
}
}
package mail;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
public class MailAuthenticator extends Authenticator {
public static String MAIL_USER = "[email protected]";
public static String MAIL_PASSWORD = "xx";
public MailAuthenticator()
{
}
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(MAIL_USER, MAIL_PASSWORD);
}
}
package service;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Vector;
import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import bean.EmailBean;
import entity.Email;
public class EmailService {
private HttpServletRequest req;
private HttpServletResponse res;
public HttpServletRequest getReq() {
return req;
}
public void setReq(HttpServletRequest req) {
this.req = req;
}
public HttpServletResponse getRes() {
return res;
}
public void setRes(HttpServletResponse res) {
this.res = res;
}
public EmailService()
{
}
public EmailService(HttpServletRequest req,HttpServletResponse res)
{
this.req=req;
this.res=res;
}
public void sendEmail(String stmp,String from,String to,
String subject,String content,String atachs){
Email email=new Email();
email.setSmtpHost(stmp);
email.setMailFrom(from);
email.setMailTo(to);
email.setSubject(subject);
email.setMsgContent(content);
Vector vec=new Vector();
String[] atach_list=atachs.split(";");
for(String atach:atach_list)
{
vec.add(atach);
}
String result="";
email.setAttachedFileList(vec);
EmailBean bean=new EmailBean(email);
try {
result=bean.sendEmail();
} catch (IOException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
try {
PrintWriter out = this.res.getWriter();
if(result.equals(""))
{
out.print("success");
}
else
{
out.print(result);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
package servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import service.EmailService;
import service.UserService;
public class EmailServlet extends HttpServlet {
private EmailService service;
/**
* Constructor of the object.
*/
public EmailServlet() {
super();
}
/**
* Destruction of the servlet.
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet.
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request,response);
}
/**
* The doPost method of the servlet.
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
request.setCharacterEncoding("UTF-8");
service=new EmailService(request,response);
String action="";
action=request.getParameter("action");
if(action==null || action.equals(""))
{
return;
}
//集中处理请求类型
if(action.toUpperCase().equals("SENDEMAIL"))
{
String stmp=request.getParameter("stmp_host");
String from=request.getParameter("mail_from");
String to=request.getParameter("mail_to");
String subject=request.getParameter("mail_subject");
String content=request.getParameter("mail_content");
String atachs=request.getParameter("mail_atach_list");
service.sendEmail(stmp,from,to,subject,content,atachs);
}
}
/**
* Initialization of the servlet.
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
stmp服务器:
发送者地址:
接收者地址:
主题:
内容:
附件
怎样设置邮箱收发服务器(pop3\stmp)
163邮箱
POP3服务器:pop3.163.com
SMTP服务器:smtp.163.com
Yahoo邮箱
POP3服务器:pop.mail.yahoo.com.cn
SMTP服务器:smtp.mail.yahoo.com
搜狐邮箱
POP3服务器:pop3.sohu.com
SMTP服务器:smtp.sohu.com
新浪邮箱
POP3服务器:pop.sina.com.cn 或pop3.sina.com.cn
SMTP服务器:smtp.sina.com.cn
请选择smtp服务器要求身份验证选项
139邮箱
POP3服务器:pop3.139.com
SMTP服务器:smtp.139.com
Gmail邮箱
POP3服务器:pop.gmail.com 端口:995 开启ssl
SMTP服务器:smtp.gmail.com 端口:465 或者587 开启ssl
帐号即用户名,密码相同,邮件地址为[email protected]
QQ邮箱
POP3服务器:pop.qq.com
SMTP服务器:smtp.qq.com
SMTP服务器需要身份验证
tom邮箱
POP3服务器:pop.tom.com.cn
SMTP服务器:smtp.tom.com.cn
java.lang.ClassNotFoundException: javax.mail.MessagingException
java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath ()Ljava/lang/String;