JavaMail 发送验证邮件(JSP/Servlet实例源码) 收藏
JavaMail 发送验证邮件(JSP/Servlet实例源码)
关键词: JavaMail 邮件 认证
JavaMail 发送验证邮件(JSP/Servlet实例源码)
关键词: JavaMail 邮件 认证
● 发送email:包括文本邮件、HTML邮件、带附件的邮件、SMTP验证
● 接收email:pop3远程连接、收取不同MIME的邮件、处理附件
● 接收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.*;"%>
<%
//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";
<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);
{
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.connect(host,user,password);
transport.send( msg );
%><p>你的邮件已发送,<a href="javascript:window.go(-1)">请返回。</></p><%
}
catch(Exception m){out.println(m.toString());}%>
</BODY>
</HTML>
}
catch(Exception m){out.println(m.toString());}%>
</BODY>
</HTML>
--------------------------------------------------------------------------------
例子二、用Servlet来发送邮件 ,PostMail.java 源代码
package mail;
import javax.mail.*;
import javax.mail.internet.*;
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;
}
/*
* 创建日期 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;
}
{
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);
{
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());
//得到中文标题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();
{
/* PostMail sm=new PostMail();
sm.setHost("smtp.126.com");//指定要使用的邮件服务器
sm.setAccount("xxxxx","xxxxx");//指定帐号和密码
sm.setAccount("xxxxx","xxxxx");//指定帐号和密码
/*
* @param String 发件人的地址
* @param String 收件人地址
* @param String 邮件标题
* @param String 邮件正文
*/
* @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>
<%
<%
//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>
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.*;
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())+"?=");
//比如说有一个邮件帐号: smtpuser@xxx.com
//POP3_HOST_NAME和SMTP_HOST_NAME分别是这邮件地址的pop3和smtp服务器DNS
//则SMTP_AUTH_USER ="smtpuser", SMTP_AUTH_PWD就是该帐号的密码
//sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
//msg.setSubject("=?GB2312?B?"+enc.encode(subject.getBytes())+"?=");
//比如说有一个邮件帐号: smtpuser@xxx.com
//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));
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);
//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");
//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).
//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 multipart = 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);
//指定发信人
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 multipart = 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");
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;
}*/
}
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 javax.mail.internet.*;
import java.util.*;
/*
To use this program, change values for the following three constants,
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
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
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.
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 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 = " user@126.com";
private static final String emailSubjectTxt = "这里是标题,Java Mail test";
private static final String emailFromAddress = " user@126.com";
// Add List of Email address to who email needs to be sent to
private static final String[] emailList = {" username@126.com", " xxxx@126.com"};
private static final String[] emailList = {" username@126.com", " xxxx@126.com"};
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;
//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");
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);
//Session session = Session.getDefaultInstance(props, auth); //有时可能被拒绝
Session session = Session.getInstance(props,auth);
session.setDebug(debug);
// create a message
Message msg = new MimeMessage(session);
Message msg = new MimeMessage(session);
// set the from and to address
InternetAddress addressFrom = new InternetAddress(from);
msg.setFrom(addressFrom);
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);
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);
}
// 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);
}
}
{
String username = SMTP_AUTH_USER;
String password = SMTP_AUTH_PWD;
return new PasswordAuthentication(username, password);
}
}
}
--------------------------------------------------------------------------------
参考:Bromon原创 请尊重版权 怎样才算比较完整的Javamail操作指南?我想应该包括绝大多数基本的email操作,能够应付一般的应用。在本指南中打算囊括以下内容: ● 发送email:包括文本邮件、HTML邮件、带附件的邮件、SMTP验证 ● 接收email:pop3远程连接、收取不同MIME的邮件、处理附件 我想有了上述功能的介绍,应该可以应付很多email的相关应用了。所以请允许我给本文拟了一个比较狂妄的名字,这样才能保证收视率,:)。还是那句话,写这个post的原因就是没有在网上看到更全面的,你看过的话记得要告诉我。 下面的所有例子都经过实际测试,你可以说它写得不够OO,不够plugable,但是它的确是可以参考的。自从有了javamail,发垃圾邮件就方便多了。本文代码多说明少,这倒不是我偷懒,而是很多东西都涉及pop3等协议的规范,如果不了解这些规范的话,有的东西我实在不知道怎么跟你解释;如果了解的话,那我基本上就不用再解释。所以本着实用的原则就省略了,由兴趣的话自己去翻翻协议规范。 废话少说,首先需要配置环境。需要的包是mail.jar和activation.jar。高版本的J2SDK EE自带。地址嘛,再java.sun.com上搜索一下,很容易找到。放到classpath中就KO。 一、 邮件的发送 下面了弄个发邮件的Hello World,热热身: 1./************* 2. Name:TextMailSender.java 3. Author:Bromon 4. Version:1.0 5. Date:2004-4-26 6. Note:发送email到
bromon@163.com,需要安装SMTP服务器 7. *************/ 8. package org.bromon.mail; 9. import javax.mail.*; 10. import javax.mail.internet.*; 11. import java.util.*; 12. public class TextMailSender 13. { 14. public static void main(String args[]) 15. { 16. try 17. { 18. Properties prop=new Properties(); 19. //指定要使用的SMTP服务器为bromon2k 20. prop.put("mail.smtp.host","bromon2k"); 21. Session mailSession=Session.getDefaultInstance(prop); 22.23. //发件人地址 24. InternetAddress from=new InternetAddress("
bromon@bromon2k"); 25. //收件人地址 26. InternetAddress to=new InternetAddress("
bromon@163.com"); 27. 28. MimeMessage msg=new MimeMessage(mailSession); 29. msg.setFrom(from); 30. msg.addRecipient(javax.mail.Message.RecipientType.TO,to); 31. //发信日期 32. msg.setSentDate(new java.util.Date()); 33. //title 34. msg.setSubject("你好"); 35. //邮件正文 36. msg.setText("hello,bromon"); 37. Transport.send(msg); 38. }catch(Exception e) 39. { 40. System.out.println(e); 41. } 42. } 43. } 程序很简单,但是它是不能运行的(倒)。除非你的机器上安装了一个SMTP服务器,而且你的机器还叫做bromon2k。写这么一段不能执行的程序不是为了找打,而是让各位对javamail有个基本印象,我就懒得改了。下面演示的是如何通过163、sohu等email服务商提供的免费邮箱来发邮件,基本操作和上面的一样,只是多一个SMTP验证而已: 1./* 2. * Created on 2004-4-26 3. */ 4. package org.bromon.mail; 5. import javax.mail.*; 6. import java.util.*; 7. import javax.mail.internet.*; 8.9. /** 10. * @author Bromon 11. */ 12. public class SenderWithSMTPVer 13. { 14. String host=""; 15. String user=""; 16. String password=""; 17.18. public void setHost(String host) 19. { 20. this.host=host; 21. } 22.23. public void setAccount(String user,String password) 24. { 25. this.user=user; 26. this.password=password; 27. } 28.29. public void send(String from,String to,String subject,String content) 30. { 31. Properties props = new Properties(); 32. props.put("mail.smtp.host", host);//指定SMTP服务器 33. props.put("mail.smtp.auth", "true");//指定是否需要SMTP验证 34. try 35. { 36. Session mailSession = Session.getDefaultInstance(props); 37. 38. mailSession.setDebug(true);//是否在控制台显示debug信息 39. 40. Message message=new MimeMessage(mailSession); 41. message.setFrom(new InternetAddress(from));//发件人 42. message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));//收件人 43. 44. message.setSubject(subject);//邮件主题 45. message.setText(content);//邮件内容 46. message.saveChanges(); 47. 48. Transport transport = mailSession.getTransport("smtp"); 49. transport.connect(host, user, password); 50. transport.sendMessage(message, message.getAllRecipients()); 51. transport.close(); 52. }catch(Exception e) 53. { 54. System.out.println(e); 55. } 56. 57. } 58.59. public static void main(String args[]) 60. { 61. SenderWithSMTPVer sm=new SenderWithSMTPVer(); 62.63. sm.setHost("smtp.163.com");//指定要使用的邮件服务器 64. sm.setAccount("abc","123");//指定帐号和密码 65.66. /* 67. * @param String 发件人的地址 68. * @param String 收件人地址 69. * @param String 邮件标题 70. * @param String 邮件正文 71. */ 72. sm.send("
abc@163.com","bromon@163.com","标题","内容"); 73. } 74.75. } 这段程序好像也不需要解释了吧,把SMTP地址、帐号、密码等配置信息写到Properties里面,Java里面很多API都需要这么干,比如再程序中加入对代理服务器的支持等。 上面的程序修改一下服务器地址、帐号、密码就可以使用,非常简单。 如何发送一个HTML格式的Email呢?也很简单,再邮件正文中写入HTML代码,然后指定邮件的ContentType就OK,下面只给出关键代码: 1.……… 2. MimeMessage msg=new MimeMessage(mailSession); 3. msg.setContent(content,"text/html"); 4. msg.setText(“<html><body><h1>下面的,你们好吗?</body></html>”); 5. ……… 下面是发送带有附件的email,稍微复杂一点,而且和前面的程序有一些不同,请仔细一点,同时需要一点IO的知识。相同的代码就不在列出,只写关键部分,谁都想偷懒不是? 1.import javax.mail.*; 2. import javax.mail.internet.*; 3. import javax.activation.*; 4. import java.util.*; 5. ………. 6. MimeMessage msg=new MimeMessage(mailSession); 7. msg.setSentDate(new Date()); 8. msg.setSubject("hello"); 9.10. MimeBodyPart textBodyPart=new MimeBodyPart(); 11. textBodyPart.setText(“邮件正文”); 12.13. MimeBodyPart fileBodyPart=new MimeBodyPart(); 14. FileDataSource fds=new FileDataSource("GIS.rar");//要发送的附件 15. fileBodyPart.setDataHandler(new DataHandler(fds)); 16. fileBodyPart.setFileName(fds.getName()); 17. Multipart container=new MimeMultipart(); 18. container.addBodyPart(textBodyPart); 19. container.addBodyPart(fileBodyPart); 20. msg.setContent(container); 21. Transport.send(msg); 22. …………
http://www.huihoo.com/java/javamail/javamail_faq.html#free 很多朋友都使用过JavaMail进行邮件发送,在邮件正文中的乱码容易解决。但邮件主题的乱码无论怎样转码总是显示一堆乱码。到底应该怎么处理呢?JavaMail中的邮件主题需要进行BASE64编码,格式形如:=?GB2312?B?xPq1xMPcwuvS0b6t1tjWw6Osx+u+ob/stcfCvKOssqLQ3rjEw9zC66Oh?=所以,直接使用msg.setSubject("中文主题"),或者msg.setSubject("中文主题".getBytes("8859_1"), "GB2312"))都一样会出现乱码。在设置邮件主题前需要将主题字串的字节编码为BASE64格式,并添加编码头,示例代码如下:sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder(); msg.setSubject("=?GB2312?B?"+enc.encode(subject.getBytes())+"?=");怎么样,现在中文可以正常显示了吧。原文转自Java中文站
本文来自CSDN博客,转载请标明出处:
http://blog.csdn.net/JavaAlpha/archive/2009/10/12/4657865.aspx