最后就是写可以实现邮件发送功能的JAVAMAIL函数了。注意把这个类放在和刚刚sevlet类的同一个包下面。
package com.test;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
import java.util.Properties;
import javax.activation.*;
import javax.mail.Session;
import javax.mail.Multipart;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeUtility;
import java.util.Date;
public class sendmail
{
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);}
}
public void send(String to,String chaosong,String subject,String content)
throws Exception,MessagingException
{//这个函数中带的参数值是在servlet中调用时传递过来的
Properties props = new Properties();
Session sendMailSession;
Transport transport;
SmtpAuth sa = new SmtpAuth();//用这个sa来进行验证和创建session
sa.getuserinfo("xx"."xxxx");//输入发送方的用户名和密码
sendMailSession = Session.getDefaultInstance(props,sa);
transport = sendMailSession.getTransport("smtp");//使用smtp协议
transport.connect("smtp.xxx.com","xxx","xxxx");//发件人的邮箱服务器,如smtp.sohu.com。用户名,密码
props.put("mail.smtp.host","smtp.xxx.com");
props.put("mail.smtp.auth","true");
Message msg = new MimeMessage(sendMailSession);
//建立新的邮件消息。
msg.setSubject(subject);//设置邮件主题
msg.setFrom(new InternetAddress(xx@xx.com));
msg.setRecipient(Message.RecipientType.TO,new InternetAddress(to));
if (chaosong ! ="")newMessage.setRecipient
(Message.RecipientType.CC,new InternetAddress(chaosong));
msg.setSentDate(new Date());
msg.setText(content);
transport.sendMessage(msg,msg.getAllRecipients());
}