JavaMail 发送验证邮件(JSP/Servlet实例源码)

转载自 bladecrazy最终编辑 bladecrazy● 发送email:包括文本邮件、HTML邮件、带附件的邮件、SMTP验证
● 接收email:pop3远程连接、收取不同MIME的邮件、处理附件

首先需要配置环境。需要mail.jar和activation.jar两个包。地址在java.sun.com上,很容易找到。放到classpath中,比如我的是这样.;E:\Tomcat5\common\lib\activation.jar;E:\Tomcat5\common\lib\mail.jar;E: \Tomcat5\common\lib\mailapi.jar;E:\Tomcat5\common\lib\;E:\jdk1.5\lib\dt.jar; E:\jdk1.5\lib\tool.jar;E:\jdk1.5\lib\;E:\jdk1.5\bin\;E:\jdk1.5。


--------------------------------------------------------------------------------
例子一、javamail.jsp 发送验证邮件源代码

<%@ page language="java" contentType="text/html; charset=GBK" pageEncoding="GBK" %>
<%
//set Chinese Char
//homepage:jiarry.126.com
request.setCharacterEncoding("GBK");
response.setCharacterEncoding("GBK");
response.setContentType("text/html; charset=GBK");
%>
<%@ page import="javax.mail.*, javax.mail.internet.*,javax.activation.*,java.util.*,java.io.*;"%>

<html>
<head>
<title>JavaMail 电子邮件发送系统</title>
</head>
<body>
JavaMail 电子邮件发送系统
<br>本例子是用java mail来发送邮件的最简单的例子,认证才能正常发送邮件。
<form action="" method="post" OnSubmit="">
收件人Email:<br /> <input type="text" name="recipients"><br />
发件人Mail:<br /> <input name="frommail" type="text" size="30" /><br />
邮件标题 <br /> <input name="subject" type="text" size="50" /><br />
内容:<br /> <textarea name="contents" cols="50" rows="10"></textarea>
<br /> <input type="submit" name="Submit" value="发送邮件" />
<form>
<%!
String host = "smtp.126.com";
String user = "username";
String password = "xxxxx";
String contentType="text/html; charset=gbk";

private class Authenticator extends javax.mail.Authenticator
{
public PasswordAuthentication getPasswordAuthentication()
{
String un = user;
String pw = password;
return new PasswordAuthentication(un, pw);
}
}
%>
<%
String touser = request.getParameter("recipients")!=null ? request.getParameter("recipients") : "";
out.print("<br>recipients:" + touser);
String fromuser = request.getParameter("frommail")!=null ? request.getParameter("frommail") : "";
out.print("<br>frommail:" + fromuser);
String subject = request.getParameter("subject")!=null ? request.getParameter("subject") : "";
out.print("<br>subject:" + subject);
String contents = request.getParameter("contents")!=null ? request.getParameter("contents") : "";
out.print("<br>contents:" + contents);
out.print("<br>");

try{
Properties props = new Properties();
props.put("mail.smtp.auth","true"); //是否验证
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", user);
props.put("mail.smtp.password",password);


boolean sessionDebug = false;
Authenticator auth = new Authenticator();
//Session mailSession = Session.getDefaultInstance(props, auth); //有时可能被拒绝
Session mailSession = Session.getInstance(props,auth); //用户验证;
//Session mailSession = Session.getInstance(props);
mailSession.setDebug(sessionDebug);


Message msg = new MimeMessage(mailSession);
msg.setFrom(new InternetAddress( fromuser ));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress( touser ));
msg.setSubject( "邮件标题:" +subject);
//((MimeMessage)msg).setSubject(subject, "GBK"); //设置中文标题
msg.setSentDate(new Date());

String text = "javamail.jsp 发送认证邮件<b>测试</b>。<hr>" + contents;

msg.setContent(text, contentType);
Transport transport = mailSession.getTransport("smtp");
transport.connect(host,user,password);

transport.send( msg );

%><p>你的邮件已发送,<a href="javascript:window.go(-1)">请返回。</></p><%
}
catch(Exception m){out.println(m.toString());}%>
</BODY>
</HTML>


--------------------------------------------------------------------------------

例子二、用Servlet来发送邮件 ,PostMail.java 源代码

package mail;
import javax.mail.*;
import javax.mail.internet.*;

import java.util.*;
/*
* 创建日期 2005-12-1
*
* TODO 要更改此生成的文件的模板,请转至
* 窗口 - 首选项 - Java - 代码样式 - 代码模板
*/
/**
* @author Administrator
*
* TODO 要更改此生成的类型注释的模板,请转至
* 窗口 - 首选项 - Java - 代码样式 - 代码模板
*/
public class PostMail {
/*String mailform=""; String mailto="";String mailsubject="";String mailcontent="";*/
String host="smtp.126.com";
String user="username";
String password="xxxxx";
public void setHost(String host)
{
this.host=host;
}

  public void setAccount(String user,String password)
{
this.user=user;
this.password=password;
}

  public void send(String from,String to,String subject,String content)
{
Properties props = new Properties();
props.put("mail.smtp.host", host);//指定SMTP服务器
props.put("mail.smtp.auth", "true");//指定是否需要SMTP验证
try
{
//Session mailSession = Session.getDefaultInstance(props);//用这个有时被拒绝;
Session mailSession = Session.getInstance(props);

mailSession.setDebug(true);//是否在控制台显示debug信息

Message message=new MimeMessage(mailSession);
message.setFrom(new InternetAddress(from));//发件人
message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));//收件人   //message.setSubject(subject); 

((MimeMessage)message).setSubject(subject, "GBK");
//得到中文标题for linux,windows下不用;   
// message.setSubject(subject);//邮件主题   

//内容类型Content-type
//普通文本为text/plain,html格式为text/html
message.setContent(content,"text/html;charset=GBK");
//message.setText("<html><body><h1>Java Mail,你好!</body></html>");

message.setText(content);//邮件内容
message.saveChanges();

Transport transport = mailSession.getTransport("smtp");
transport.connect(host, user, password);
transport.sendMessage(message, message.getAllRecipients());


transport.close();
}catch(Exception e)
{
System.out.println(e);
}

}

  public static void main(String args[])
{
/*  PostMail sm=new PostMail();

   sm.setHost("smtp.126.com");//指定要使用的邮件服务器
sm.setAccount("xxxxx","xxxxx");//指定帐号和密码

   /*
* @param String 发件人的地址
* @param String 收件人地址
* @param String 邮件标题
* @param String 邮件正文
*/

}

  } 

调用PostMail.java的jsp文件:postmail.jsp源代码

<%@ page language="java" contentType="text/html; charset=GBK" pageEncoding="GBK" %>
<%
//set Chinese Char
//homepage:jiarry.126.com
request.setCharacterEncoding("GBK");
response.setCharacterEncoding("GBK");
response.setContentType("text/html; charset=GBK");
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>电子邮件</title>
<script language="JavaScript">
<!--
function checkdata() {
var txt  = document.forms[0].email.value;
if(txt.search("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$")!=0) {
alert("请输入正确电子邮件");
document.forms[0].email.select();
return false;
}

return true;
}
-->
</script>
</head>
<body>
<p>
<%
java.util.Date date = new java.util.Date();
out.print(new java.util.Date());
out.print("<hr>");
%>
本例子是调用PostMail.java来发送认证的邮件,需要下载mail.jar和activation.jar,并设置classpath
<jsp:useBean id="mail" scope="page" class="mail.PostMail" />
<form action="" method="post" OnSubmit="return checkdata()">
<p>请输入发件人电子邮件:<input type="text" name="email">
<p>请输入收件人电子邮件:<input type="text" name="toemail">
<p><input type="submit" value="发送">
<form>
<%

String email ="",toemail="";
if(request.getParameter("email")!=null){
email =request.getParameter("email");
}
if(request.getParameter("toemail")!=null){
toemail =request.getParameter("toemail");
}
//if(email!=null)
if( email.trim().length()>0 && !email.matches("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$")) {
out.print("发件人邮件地址不正确");
return;
}
if(toemail.trim().length()>0 && !toemail.matches("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$")) {
out.print("收件人邮件地址不正确");
return;
}

if(email.trim().length()>0 && toemail.trim().length()>0){
try{
mail.send(email,toemail, "Test PostMail.java 中文", "<h1>Java Mail,你好 PostMail!</h1><br><br><b>Jiarry.126.com</b>");
out.print("<font color='green'>邮件发送</font>");
}catch(Exception e){
out.print( "<font color='red'>出错了</font>");
out.print(e.getMessage());
System.out.print(e.getMessage());
}
}

%>
</body>
</html>


--------------------------------------------------------------------------------

其他java源代码:MailManager.java 源代码

package mail;

import javax.mail.*; 
import javax.mail.internet.*; 
import java.util.*;
import javax.activation.*;
import java.io.*;

public class MailManager {

//sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
//msg.setSubject("=?GB2312?B?"+enc.encode(subject.getBytes())+"?=");

//比如说有一个邮件帐号: [email protected]
//POP3_HOST_NAME和SMTP_HOST_NAME分别是这邮件地址的pop3和smtp服务器DNS
//则SMTP_AUTH_USER ="smtpuser", SMTP_AUTH_PWD就是该帐号的密码

private  final String POP3_HOST_NAME = "pop3.126.com";
private  final String SMTP_HOST_NAME = "smtp.126.com";
private  final String SMTP_AUTH_USER = "username";
private  final String SMTP_AUTH_PWD  = "xxxxxx";

private Authenticator auth = new Authenticator(){
public PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(SMTP_AUTH_USER, SMTP_AUTH_PWD);
}
};

public void sendMail(String toAddr, String subject,
String body, String fromAddr, String contentType) {
try { 
Properties props = new Properties(); 

//指定SMTP服务器,邮件通过它来投递
props.put("mail.smtp.host", (String)SMTP_HOST_NAME);
props.put("mail.smtp.auth", (String)"true");  
//Session session =Session.getDefaultInstance(props, auth);
Session session =Session.getInstance(props, auth); //
Message msg = new MimeMessage(session); 

//指定发信人
msg.setFrom(new InternetAddress(fromAddr));

   //指定收件人
//InternetAddress[] tos = {new InternetAddress(toAddr)}; 
//msg.setRecipients(Message.RecipientType.TO,tos);

//指定收件人,多人时用逗号分隔
InternetAddress[] tos =InternetAddress.parse(toAddr); 
msg.setRecipients(Message.RecipientType.TO,tos);

   //标题//转码BASE64Encoder
//sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
//msg.setSubject("=?GBK?B?"+enc.encode(subject.getBytes())+"?=");
//msg.setSubject(new String(subject.getBytes("GBK"),"ISO8859-1"));
//msg.setSubject("=?GB2312?B?"+enc.encode(subject.getBytes())+"?=");
//msg.setSubject(subject);
((MimeMessage)msg).setSubject(subject,"GBK");
//得到中文标题for linux,windows下不用;

//内容
msg.setText(body);

//发送时间
msg.setSentDate(new Date());

//内容类型Content-type
//普通文本为text/plain,html格式为text/html;charset=GBK
msg.setContent(body, contentType);

//发送
Transport.send(msg); 

} catch(Exception e){ 
System.out.println(e); 

}

public void sendMailWithAttatchment(String toAddr, String subject, String body,
String fromAddr, String contentType, String []fileList) {
try { 
Properties props = new Properties(); 

//指定SMTP服务器,邮件通过它来投递
props.put("mail.smtp.host", SMTP_HOST_NAME);
props.put("mail.smtp.auth", "true");

   Session session = Session.getDefaultInstance(props, auth);
//Session session = Session.getInstance(props, auth);//
SecurityManager security = System.getSecurityManager();
System.out.println("Security Manager" + security);
//Looking at your code it looks like you will see a null value for security.
//If the security is null use session.getInstance(props,auth)
//instead of session.getDefaultInstance(props,auth).

   Message msg = new MimeMessage(session); 

//指定发信人
msg.setFrom(new InternetAddress(fromAddr));

//指定收件人
//InternetAddress[] tos = {new InternetAddress(toAddr)}; 
//msg.setRecipients(Message.RecipientType.TO,tos);

//指定收件人,多人时用逗号分隔
InternetAddress[] tos =InternetAddress.parse(toAddr); 
msg.setRecipients(Message.RecipientType.TO,tos);

//标题//转码BASE64Encoder
//sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
//msg.setSubject("=?GBK?B?"+enc.encode(subject.getBytes())+"?=");
//msg.setSubject(new String(subject.getBytes("GBK"),"ISO8859-1"));
//msg.setSubject("=?GB2312?B?"+enc.encode(subject.getBytes())+"?=");
//msg.setSubject(subject);
((MimeMessage)msg).setSubject(subject, "GBK");
//得到中文标题for linux,windows下不用;

//发送时间
//msg.setSentDate(new Date());
msg.setSentDate(new java.util.Date());
Multipart mutipart = new MimeMultipart();
MimeBodyPart bodyPart = new MimeBodyPart();
//内容
bodyPart.setText(body);
//Content-type
bodyPart.setContent(body, contentType);
multipart.addBodyPart(bodyPart);

for(int i=0; i<fileList.length; ++i) {
bodyPart = new MimeBodyPart();
File f = new File(fileList[i]);
DataSource source = new FileDataSource(f);
bodyPart.setDataHandler(new DataHandler(source));
bodyPart.setFileName(f.getName());

multipart.addBodyPart(bodyPart);
}

msg.setContent(multipart);

   //发送
Transport.send(msg); 

} catch(Exception e){ 
System.out.println(e); 

}
/*
public Mails getMails() {
Mails mails=null;
try { 
//Properties props = System.getProperties();
Properties props = new Properties();   
props.put("mail.pop3.host", SMTP_HOST_NAME);
props.put("mail.pop3.auth", "true");

   Session session = Session.getDefaultInstance(props, auth);

Store store = session.getStore("pop3");
store.connect();

Folder inbox = store.getFolder("INBOX");
mails = new Mails(inbox);
store.close();

} catch(Exception e){
System.out.println(e);
}
return mails;
}*/
}


--------------------------------------------------------------------------------

SendMailUsingAuthentication.java 源代码,引用这个java bean发送认证email例子
package mail;

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

import java.util.*;

/*
To use this program, change values for the following three constants,

    SMTP_HOST_NAME -- Has your SMTP Host Name
SMTP_AUTH_USER -- Has your SMTP Authentication UserName
SMTP_AUTH_PWD  -- Has your SMTP Authentication Password

  Next change values for fields

  emailMsgTxt  -- Message Text for the Email
emailSubjectTxt  -- Subject for email
emailFromAddress -- Email Address whose name will appears as "from" address

  Next change value for "emailList".
This String array has List of all Email Addresses to Email Email needs to be sent to.


Next to run the program, execute it as follows,

  SendMailUsingAuthentication authProg = new SendMailUsingAuthentication();

*/

public class SendMailUsingAuthentication
{

  private static final String SMTP_HOST_NAME = "smtp.126.com";
private static final String SMTP_AUTH_USER = "username";
private static final String SMTP_AUTH_PWD  = "******";

  private static final String emailMsgTxt      = "Online Order Confirmation Message. Also include the Tracking Number.中国人";
private static final String emailSubjectTxt  = "这里是标题,Java Mail test";
private static final String emailFromAddress = "[email protected]";

  // Add List of Email address to who email needs to be sent to
private static final String[] emailList = {"[email protected]", "[email protected]"};


public static void main(String args[]) throws Exception
{
//SendMailUsingAuthentication smtpMailSender = new SendMailUsingAuthentication();
//smtpMailSender.postMail( emailList, emailSubjectTxt, emailMsgTxt, emailFromAddress);
//smtpMailSender.postMail( emailList, emailSubjectTxt, emailMsgTxt, emailFromAddress);
//System.out.println("Sucessfully Sent mail to All Users");
}

  public void postMail( String recipients[], String subject,
//public void postMail( String recipients, String subject,
String message , String from) throws MessagingException
{
boolean debug = false;

     //Set the host smtp address
Properties props = new Properties();
props.put("mail.smtp.host", SMTP_HOST_NAME);
props.put("mail.smtp.auth", "true");

    Authenticator auth = new SMTPAuthenticator();
//Session session = Session.getDefaultInstance(props, auth); //有时可能被拒绝
Session session = Session.getInstance(props,auth);

session.setDebug(debug);

    // create a message
Message msg = new MimeMessage(session);

    // set the from and to address
InternetAddress addressFrom = new InternetAddress(from);
msg.setFrom(addressFrom);

    InternetAddress[] addressTo = new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++)
{
addressTo[i] = new InternetAddress(recipients[i]);
}
msg.setRecipients(Message.RecipientType.TO, addressTo);

   // msg.setRecipient(Message.RecipientType.TO,toemail);
// Setting the Subject and Content Type

//标题//转码BASE64Encoder
//sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
//msg.setSubject("=?GBK?B?"+enc.encode(subject.getBytes())+"?=");
//msg.setSubject(new String(subject.getBytes("GBK"),"ISO8859-1"));
//msg.setSubject("=?GB2312?B?"+enc.encode(subject.getBytes())+"?=");
//msg.setSubject(subject);
((MimeMessage)msg).setSubject(subject, "GBK");
//得到中文标题for linux,windows下不用;

// msg.setSubject(subject);
msg.setContent(message, "text/html;charset=GBK");
//msg.setContent(message, "text/plain");
Transport.send(msg);
}


/**
* SimpleAuthenticator is used to do simple authentication
* when the SMTP server requires it.
*/
private class SMTPAuthenticator extends javax.mail.Authenticator
{

    public PasswordAuthentication getPasswordAuthentication()
{
String username = SMTP_AUTH_USER;
String password = SMTP_AUTH_PWD;
return new PasswordAuthentication(username, password);
}
}

}

你可能感兴趣的:(jsp,linux,servlet,Security,sun)