实际应用:
import java.util.Date;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.SendFailedException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class main extends HttpServlet
{
protected Session session = null;
//邮件用户名
String mailUser = "";//自己的邮箱名字
String host = "smtp.163.com";
String pwd = "";//自己邮箱密码
public main() throws ServletException
{
init();
}
public void init()
{
Properties props = new Properties();
props.put("mail.transpost.protocol", "smtp");
props.put("mail.smtp.host", "smtp.163.com");
//必须要有一个类来认证
props.put("mail.smtp.auth", "true");
props.put("mail.smpt.port", "25");
Email_Autherticatorbean auth = new Email_Autherticatorbean(mailUser,pwd);
//session认证
session = Session.getInstance(props,auth);
//这个是跟踪后台消息。打印在控制台
session.setDebug(true);
}
public void sendMails()
{
try
{
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("
[email protected]"));
msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("
[email protected]"));
msg.setRecipients(Message.RecipientType.CC,
InternetAddress.parse("
[email protected]"));
msg.setSentDate(new Date());
msg.setSubject("this is my Frist mail");
msg.setContent("this is my mail","text/html");
msg.setText("我成功了!!哈哈,java还是不错的啊~~");
msg.setSentDate(new java.util.Date());
Transport transport = session.getTransport("smtp");
//与发送者的邮箱相连
transport.connect(host,mailUser,pwd);
transport.send(msg);
}
catch (SendFailedException e)
{
e.printStackTrace();
}
catch (Exception ee)
{
ee.printStackTrace();
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
new main().sendMails();
System.out.println("send mail success!");
}
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException ,IOException
{
doGet(request,response);
}
}
我用到的Email_Autherticatorbean 类:
package nerve;
import javax.mail.*;
public class Email_Autherticatorbean extends Authenticator
{
private String m_username = null;
private String m_userpass = null;
public void setUsername(String username)
{
m_username = username;
}
public void setUserpass(String userpass)
{
m_userpass = userpass;
}
public Email_Autherticatorbean(String username, String userpass)
{
super();
setUsername(username);
setUserpass(userpass);
}
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(m_username,m_userpass);
}
}