思路::
1 用户注册后,将用户资料和随机产生的激活验证码存入到“未激活用户表”中
2 向用户注册的邮箱发送一封邮件,包含一个链接,大体如:
“http://你的站点/应用目录/激活验证.jsp?激活验证码=xxx&用户名=xxx”这样的格式
3 在激活验证页里比较接收到的验证码和“未激活用户表”中该用户对应的验证码是否匹配。是则注册成功,将该用户信息转移到“注册用户表”中。
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
javaMail很简单的一个应用,不过在web app上应用的很多。
这是我自己机器上运行通过的程序,最基础的,以后的项目中有机会考虑用FCKEditor做个页面这样邮件的内容就更加丰富多彩了。
下面是代码:
SendMail.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package javaMail;
import java.util.*;
import java.io.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
/**
* <p>Title: 使用javamail发送邮件</p>
* <p>Description: 演示如何使用javamail包发送电子邮件。这个实例可发送多附件</p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Filename: Mail.java</p>
* @version 1.0
*/
public class SendMail {
String to = "";//收件人
String from = "";//发件人
String host = "";//smtp主机
String username = "";
String password = "";
String filename = "";//附件文件名
String subject = "";//邮件主题
String content = "";//邮件正文
Vector file = new Vector();//附件文件集合
/**
*<br>方法说明:默认构造器
*<br>输入参数:
*<br>返回类型:
*/
public SendMail() {
}
/**
*<br>方法说明:构造器,提供直接的参数传入
*<br>输入参数:
*<br>返回类型:
*/
public SendMail(String to, String from, String smtpServer, String username, String password, String subject, String content) {
this.to = to;
this.from = from;
this.host = smtpServer;
this.username = username;
this.password = password;
this.subject = subject;
this.content = content;
}
/**
*<br>方法说明:设置邮件服务器地址
*<br>输入参数:String host 邮件服务器地址名称
*<br>返回类型:
*/
public void setHost(String host) {
this.host = host;
}
/**
*<br>方法说明:设置登录服务器校验密码
*<br>输入参数:
*<br>返回类型:
*/
public void setPassWord(String pwd) {
this.password = pwd;
}
/**
*<br>方法说明:设置登录服务器校验用户
*<br>输入参数:
*<br>返回类型:
*/
public void setUserName(String usn) {
this.username = usn;
}
/**
*<br>方法说明:设置邮件发送目的邮箱
*<br>输入参数:
*<br>返回类型:
*/
public void setTo(String to) {
this.to = to;
}
/**
*<br>方法说明:设置邮件发送源邮箱
*<br>输入参数:
*<br>返回类型:
*/
public void setFrom(String from) {
this.from = from;
}
/**
*<br>方法说明:设置邮件主题
*<br>输入参数:
*<br>返回类型:
*/
public void setSubject(String subject) {
this.subject = subject;
}
/**
*<br>方法说明:设置邮件内容
*<br>输入参数:
*<br>返回类型:
*/
public void setContent(String content) {
this.content = content;
}
/**
*<br>方法说明:把主题转换为中文
*<br>输入参数:String strText
*<br>返回类型:
*/
public String transferChinese(String strText) {
try {
strText = MimeUtility.encodeText(new String(strText.getBytes(), "GB2312"), "GB2312", "B");
} catch (Exception e) {
e.printStackTrace();
}
return strText;
}
/**
*<br>方法说明:往附件组合中添加附件
*<br>输入参数:
*<br>返回类型:
*/
public void attachfile(String fname) {
file.addElement(fname);
}
/**
*<br>方法说明:发送邮件
*<br>输入参数:
*<br>返回类型:boolean 成功为true,反之为false
*/
public boolean sendMail() {
//构造mail session
Properties props = System.getProperties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props, new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
//构造MimeMessage 并设定基本的值
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = {new InternetAddress(to)};
msg.setRecipients(Message.RecipientType.TO, address);
subject = transferChinese(subject);
msg.setSubject(subject);
//构造Multipart
Multipart mp = new MimeMultipart();
//向Multipart添加正文
MimeBodyPart mbpContent = new MimeBodyPart();
mbpContent.setText(content);
//向MimeMessage添加(Multipart代表正文)
mp.addBodyPart(mbpContent);
//向Multipart添加附件
Enumeration efile = file.elements();
while (efile.hasMoreElements()) {
MimeBodyPart mbpFile = new MimeBodyPart();
filename = efile.nextElement().toString();
FileDataSource fds = new FileDataSource(filename);
mbpFile.setDataHandler(new DataHandler(fds));
mbpFile.setFileName(fds.getName());
//向MimeMessage添加(Multipart代表附件)
mp.addBodyPart(mbpFile);
}
//file.removeAllElements();
//向Multipart添加MimeMessage
msg.setContent(mp);
msg.setSentDate(new Date());
//发送邮件
Transport.send(msg);
} catch (MessagingException mex) {
mex.printStackTrace();
Exception ex = null;
if ((ex = mex.getNextException()) != null) {
ex.printStackTrace();
}
return false;
}
return true;
}
/**
*<br>方法说明:主方法,用于测试
*<br>输入参数:
*<br>返回类型:
*/
public static void main(String[] args) {
SendMail sendmail = new SendMail();
sendmail.setHost("smtp.163.com");
sendmail.setUserName("heyuhao8774");
sendmail.setPassWord("********");
sendmail.setTo("heyuhao8774@163.com");
sendmail.setFrom("heyuhao8774@163.com");
sendmail.setSubject("测试-JAVA程序发送邮件!");
sendmail.setContent("你好这是一个测试-JAVA程序发送邮件!");
sendmail.sendMail(); //发送邮件
}
}//end
**********************************************************************************************
javaMail Java实现邮件发送
默认分类 2009-09-21 18:42 阅读117 评论0 字号: 大大 中中 小小 做爬虫开发时候为了时刻得到爬虫的抓取状况,所以用到一个定时发送邮件系统,以便随时把爬虫抓取情况发送到我的邮箱,从而更好地了解爬虫运行情况,有用到的朋友尽管拷贝用了,直接能用的,记者把你的邮箱发送服务器给该一下就行了。
邮件系统很简单哦,只有下面两个类:
MailBean 和 SendMailOnTime
需要jar组件:
activation.jar
mail.jar
log4j.jar
代码如下:
/*
* Created on 2005-9-7
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*
* Update on 2008-8-14
*/
package javaMail;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.apache.log4j.Logger;
/**
* @author panshengti 类功能 : 处理意见反馈邮件发送 调用 jar:activation.jar 、 mail.jar
*/
public class MailBean {
public static Logger log = null ;
static {
log = Logger.getLogger (MailBean. class );
}
// smtpHost 发件人所用到的 smtp 服务器
String smtpHost = "smtp.163.com" ;
// from 发件人邮箱
String from = "d-ear@163.com" ;
// to 收件人邮箱
String to = "mbrasser@d-ear.com" ;
// subject 邮件标题
String subject = "receive a mail from d-ear@163.com" ;
// theMessage 邮件内容
StringBuffer theMessage = new StringBuffer();
/**
* 固定的给 ffshi@d-ear.com ,stpan@d-ear.com 发送邮件
* create date:2008- 8- 15
* author:Administrator
*
* @param smtpHost
* @param from
* @param subject
* @param messageText
* @throws MessagingException
*/
public void sendMessage(String smtpHost, String from,
String subject, String messageText) throws MessagingException {
SmtpAuth sa = new SmtpAuth();
sa.getuserinfo( "d-ear" , "123abc" );
java.util.Properties props = new java.util.Properties();
props.put( "mail.smtp.auth" , "true" );
props.put( "mail.smtp.host" , smtpHost);
System. out .println( "Constructing message- from=" + from + " to=" + to );
InternetAddress fromAddress = new InternetAddress(from);
InternetAddress[] toAddresss = new InternetAddress[2];
toAddresss[0] = new InternetAddress( "ffshi@d-ear.com" );
toAddresss[1] = new InternetAddress( "stpan@d-ear.com" );
int i = 0;
while (i < toAddresss. length ) {
Session mailSession = Session.getDefaultInstance (props, sa);
MimeMessage testMessage = new MimeMessage(mailSession);
testMessage.setFrom(fromAddress);
testMessage.addRecipient(javax.mail.Message.RecipientType. TO ,
toAddresss[i]);
testMessage.setSentDate( new java.util.Date());
testMessage.setSubject(subject);
testMessage.setText(messageText);
Transport.send (testMessage);
System. out .println( "A mail have been sent!" );
i++;
}
}
/*
* 由 163 服务器向目的邮箱发送邮件
* 邮件发送处理 @param stmHost,from,to,subject,messageText
*/
public void sendMessage(String smtpHost, String from, String to,
String subject, String messageText) throws MessagingException {
SmtpAuth sa = new SmtpAuth();
sa.getuserinfo( "d-ear" , "123abc" );
java.util.Properties props = new java.util.Properties();
props.put( "mail.smtp.auth" , "true" );
props.put( "mail.smtp.host" , smtpHost);
System. out .println( "Constructing message- from=" + from + " to=" + to);
InternetAddress fromAddress = new InternetAddress(from);
InternetAddress toAddresss = new InternetAddress(to);
Session mailSession = Session.getDefaultInstance (props, sa);
MimeMessage testMessage = new MimeMessage(mailSession);
testMessage.setFrom(fromAddress);
testMessage.addRecipient(javax.mail.Message.RecipientType. TO ,
toAddresss);
testMessage.setSentDate( new java.util.Date());
testMessage.setSubject(subject);
testMessage.setText(messageText);
Transport.send (testMessage);
System. out .println( "A mail have been sent to " + to);
}
/**
* 功能:群发功能 , 把所有的目的邮箱作为一个数组参数传入
* create date:2008- 8- 15
* author:Administrator
*
* @param smtpHost
* @param from
* @param to 目的邮箱数组
* @param subject
* @param messageText
* @throws MessagingException
*/
public void sendMessage(String smtpHost, String from, String[] to,
String subject, String messageText) throws MessagingException {
SmtpAuth sa = new SmtpAuth();
sa.getuserinfo( "d-ear" , "123abc" );
java.util.Properties props = new java.util.Properties();
props.put( "mail.smtp.auth" , "true" );
props.put( "mail.smtp.host" , smtpHost);
System. out .println( "Constructing message- from=" + from + " to=" + to);
InternetAddress fromAddress = new InternetAddress(from);
InternetAddress[] toAddresss = new InternetAddress[to. length ];
for ( int len=0;len<to. length ;len++){
toAddresss[0] = new InternetAddress(to[len]);
}
int i = 0;
while (i < toAddresss. length ) {
Session mailSession = Session.getDefaultInstance (props, sa);
MimeMessage testMessage = new MimeMessage(mailSession);
testMessage.setFrom(fromAddress);
testMessage.addRecipient(javax.mail.Message.RecipientType. TO ,
toAddresss[i]);
testMessage.setSentDate( new java.util.Date());
testMessage.setSubject(subject);
testMessage.setText(messageText);
Transport.send (testMessage);
System. out .println( "A mail have been sent to " +to[i]);
i++;
}
}
/*
* 邮件用户名和密码认证
*/
static class SmtpAuth extends javax.mail.Authenticator {
private String user , password ;
public void getuserinfo(String getuser, String getpassword) {
user = getuser;
password = getpassword;
}
protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
return new javax.mail.PasswordAuthentication( user , password );
}
}
}
package javaMail;
import javax.mail.MessagingException;
import org.apache.log4j.Logger;
public class SendMailOnTime {
public static Logger log = null ;
static {
log = Logger.getLogger (SendMailOnTime. class );
}
/**
* @param args
*/
public static void sendMail(String str) {
MailBean mail = new MailBean();
try {
mail.sendMessage( "smtp.163.com" , "d-ear@163.com" ,
"rent information" , str);
} catch (MessagingException e) {
System. out .println( "mail send error !" );
log .debug( "mail send error !" + e.getMessage());
e.printStackTrace();
}
System. out .println( "Mail have been sended ." );
}
/**
* 给一个指定邮箱发送指定的邮件内容 create date:2008- 8- 15 author:Administrator
*
* @param str
*/
public static void sendMail(String toMail, String content) {
MailBean mail = new MailBean();
try {
mail.sendMessage( "smtp.163.com" , "d-ear@163.com" , toMail,
"spider information" , content);
} catch (MessagingException e) {
System. out .println( "mail send error !" );
log .debug( "mail send error !" + e.getMessage());
e.printStackTrace();
}
System. out .println( "Mail have been sended ." );
}
/**
* 指定目的邮箱数组进行群发 create date:2008- 8- 15 author:Administrator
*
* @param toMail
* @param content
*/
public static void sendMail(String[] toMail, String content) {
MailBean mail = new MailBean();
try {
mail.sendMessage( "smtp.163.com" , "d-ear@163.com" , toMail,
"spider information" , content);
} catch (MessagingException e) {
System. out .println( "mail send error !" );
log .debug( "mail send error !" + e.getMessage());
e.printStackTrace();
}
System. out .println( "Mail have been sended ." );
}
}
¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥
如下程序需要:javamail,JAF包,j2ee.jar包含了上述两个包,建议大家安装J2SDKEE或直接拷贝j2ee.jar,将其添加到jbuilder的library中,或系统ClassPath中
*/
package com.me.util.mail;
/**
* @author Zhangkun aistill@msn.com
* @version 1.0
*/
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Date;
import javax.activation.*;
import java.io.*;
import com.me.util.*;
public class sendMail {
private MimeMessage mimeMsg; //MIME邮件对象
private Session session; //邮件会话对象
private Properties props; //系统属性
private boolean needAuth = false; //smtp是否需要认证
private String username = ""; //smtp认证用户名和密码
private String password = "";
private Multipart mp; //Multipart对象,邮件内容,标题,附件等内容均添加到其中后再生成MimeMessage对象
/**
*
*/
public sendMail() {
setSmtpHost(getConfig.mailHost);//如果没有指定邮件服务器,就从getConfig类中获取
createMimeMessage();
}
public sendMail(String smtp){
setSmtpHost(smtp);
createMimeMessage();
}
/**
* @param hostName String
*/
public void setSmtpHost(String hostName) {
System.out.println("设置系统属性:mail.smtp.host = "+hostName);
if(props == null)props = System.getProperties(); //获得系统属性对象
props.put("mail.smtp.host",hostName); //设置SMTP主机
}
/**
* @return boolean
*/
public boolean createMimeMessage()
{
try{
System.out.println("准备获取邮件会话对象!";
session = Session.getDefaultInstance(props,null); //获得邮件会话对象
}
catch(Exception e){
System.err.println("获取邮件会话对象时发生错误!"+e);
return false;
}
System.out.println("准备创建MIME邮件对象!";
try{
mimeMsg = new MimeMessage(session); //创建MIME邮件对象
mp = new MimeMultipart();
return true;
}
catch(Exception e){
System.err.println("创建MIME邮件对象失败!"+e);
return false;
}
}
/**
* @param need boolean
*/
public void setNeedAuth(boolean need) {
System.out.println("设置smtp身份认证:mail.smtp.auth = "+need);
if(props == null)props = System.getProperties();
if(need){
props.put("mail.smtp.auth","true";
}else{
props.put("mail.smtp.auth","false";
}
}
/**
* @param name String
* @param pass String
*/
public void setNamePass(String name,String pass) {
username = name;
password = pass;
}
/**
* @param mailSubject String
* @return boolean
*/
public boolean setSubject(String mailSubject) {
System.out.println("设置邮件主题!";
try{
mimeMsg.setSubject(mailSubject);
return true;
}
catch(Exception e) {
System.err.println("设置邮件主题发生错误!";
return false;
}
}
/**
* @param mailBody String
*/
public boolean setBody(String mailBody) {
try{
BodyPart bp = new MimeBodyPart();
bp.setContent("<meta http-equiv=Content-Type content=text/html; charset=gb2312>"+mailBody,"text/html;charset=GB2312";
mp.addBodyPart(bp);
return true;
}
catch(Exception e){
System.err.println("设置邮件正文时发生错误!"+e);
return false;
}
}
/**
* @param name String
* @param pass String
*/
public boolean addFileAffix(String filename) {
System.out.println("增加邮件附件:"+filename);
try{
BodyPart bp = new MimeBodyPart();
FileDataSource fileds = new FileDataSource(filename);
bp.setDataHandler(new DataHandler(fileds));
bp.setFileName(fileds.getName());
mp.addBodyPart(bp);
return true;
}
catch(Exception e){
System.err.println("增加邮件附件:"+filename+"发生错误!"+e);
return false;
}
}
/**
* @param name String
* @param pass String
*/
public boolean setFrom(String from) {
System.out.println("设置发信人!";
try{
mimeMsg.setFrom(new InternetAddress(from)); //设置发信人
return true;
}
catch(Exception e)
{ return false; }
}
/**
* @param name String
* @param pass String
*/
public boolean setTo(String to){
if(to == null)return false;
try{
mimeMsg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(to));
return true;
}
catch(Exception e)
{ return false; }
}
/**
* @param name String
* @param pass String
*/
public boolean setCopyTo(String copyto)
{
if(copyto == null)return false;
try{
mimeMsg.setRecipients(Message.RecipientType.CC,(Address[])InternetAddress.parse(copyto));
return true;
}
catch(Exception e)
{ return false; }
}
/**
* @param name String
* @param pass String
*/
public boolean sendout()
{
try{
mimeMsg.setContent(mp);
mimeMsg.saveChanges();
System.out.println("正在发送邮件....";
Session mailSession = Session.getInstance(props,null);
Transport transport = mailSession.getTransport("smtp";
transport.connect((String)props.get("mail.smtp.host",username,password);
transport.sendMessage(mimeMsg,mimeMsg.getRecipients(Message.RecipientType.TO));
//transport.send(mimeMsg);
System.out.println("发送邮件成功!";
transport.close();
return true;
}
catch(Exception e)
{
System.err.println("邮件发送失败!"+e);
return false;
}
}
/**
* Just do it as this
*/
public static void main(String[] args) {
String mailbody = "<meta http-equiv=Content-Type content=text/html; charset=gb2312>"+
"<div align=center><a href=http://www.csdn.net> csdn </a></div>";
sendMail themail = new sendMail("smtp.msn.com";
themail.setNeedAuth(true);
if(themail.setSubject("标题" == false) return;
if(themail.setBody(mailbody) == false) return;
if(themail.setTo("gates@msn.com" == false) return;
if(themail.setFrom("bill@msn.com" == false) return;
if(themail.addFileAffix("c://boot.ini" == false) return;
themail.setNamePass("user","password";
if(themail.sendout() == false) return;
}
}