1.需要mail.jar和activation.jar可在j2ee的lib里面找到
C:/Sun/AppServer/lib
2.要在tomcat中使用,需要将这两个jar放到tomcat/common/lib里面,并添加到classpath中
import javax.mail.*;
import javax.activation.*;
import javax.mail.internet.*;
/*-- 设置属性 --*/
properties = System.getProperties();
properties.put("mail.smtp.auth", strAuthen);
properties.put("mail.smtp.host", strHost);
/*-- 密码验证 --*/
SmtpAuthenticator sa = new SmtpAuthenticator(strUsr, strPwd);
Session session = Session.getInstance(properties,sa);
session.setDebug(false);
/*-- 构造邮件 --*/
Message msg = new MimeMessage(session);
msg.setSentDate(new Date());
msg.setFrom(new InternetAddress(strFrom));
msg.setRecipient(Message.RecipientType.TO,new InternetAddress(strTo));
msg.setSubject(strSubject);
msg.setContent(strBody,"text/plain;charset=Gb2312");
/*-- 传送邮件 --*/
transport = session.getTransport("smtp");
if(strAuthen.equals("true"))//是否需要验证
{
transport.connect(strHost, strUsr, strPwd);
transport.sendMessage(msg, msg.getAllRecipients());
}
else
{
transport.send(msg);
}
transport.close();
3.JSP中使用
SendMail sender = new SendMail("ohahu@sohu.com", //--发信人
"ohahu@163.com", //--收信人
"this 刘国强 Title", //--标题
"this 刘国强 body", //--内容
null); //--附件
sender.putAuthentication("smtp.sohu.com", //--smtp服务器
"ohahu", //--用户名
"", //--密码不要忘记输了
"true"); //是否需要验证
sender.startSend();
4.需要改进的地方,没有加入附件的代码,可以参考
http://community.youkuaiyun.com/Expert/FAQ/FAQ_Index.asp?id=12942
其中的strAttach应该是附件的路径信息。
接下来的任务:
1.完善附件添加部分内容
2.通过邮件验证用户注册申请及密码修改功能
2.文件上传代码
3.数据库记录按照XML文件显示,及数据库生成目录树
7月25日添:邮件附件的添加
为了一个附件的内容加一个第四天实在不值得,主要代码如下:
/*-- 添加附件 --*/
Multipart multiPart = new MimeMultipart();
//信件内容
MimeBodyPart textBody = new MimeBodyPart();
textBody.setText(strBody);
multiPart.addBodyPart(textBody);
//信件附件
Enumeration elemFile = vFile.elements();//Vector vFile;用vFile.addElement(String newFile);添加附件
iAttachCount = 0;
while(elemFile.hasMoreElements())
{
String strFileName = elemFile.nextElement().toString();//附件的路径
File file = new File(strFileName);
if(!file.exists())//判断文件是否存在
continue;
iAttachCount++;
MimeBodyPart fileBody = new MimeBodyPart();
FileDataSource fileData = new FileDataSource(strFileName);
fileBody.setDataHandler(new DataHandler(fileData));
fileBody.setFileName(fileData.getName());
multiPart.addBodyPart(fileBody);
}
vFile.removeAllElements();
msg.setContent(multiPart);
}
有了这部分内容,就不用再用上面msg.setContent(strBody,"text/plain;charset=Gb2312");部分了,不过如果没有附件也用MimeBodyPart,在接收邮件的时候同样会显示出有附件,因此,没有附件最好用setContent函数构造邮件。