使用javamail发送邮件

1.下载javamail 的jar包: http://cds-esd.sun.com/ESD36/JSCDL/javamail/1.4.1/javamail-1_4_1.zip?AuthParam=1208313388_ba889c08bdcf431df94e26ed2a5b590f&TicketId=B%2Fw6lxSIRF1JSB1LMl5blAbl&GroupName=CDS&FilePath=/ESD36/JSCDL/javamail/1.4.1/javamail-1_4_1.zip&File=javamail-1_4_1.zip
2.创建两个类
package com.email;

import java.util.Properties;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 * @author Sech
 * 
 */
public class SendEmail {

	/**
	 * 
	 */
	public SendEmail() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * 发送Email
	 */
	public void Send(String content) {
		try {
			String host = "smtp.163.com";
			String from = "[email protected]";// 发送的邮箱
			String to = "[email protected]";// 接收的邮箱
			String userName = "send";// 发送邮箱的用户名
			String password = "sendPassword";// 发送邮箱的密码
			Properties props = new Properties();

			props.put("mail.smtp.host", host);
			props.put("mail.smtp.auth", "true");
			props.put("username", userName);
			props.put("password", password);

			SmtpAuth sa = new SmtpAuth();
			sa.setUserinfo(userName, password);
			Session session = Session.getDefaultInstance(props, sa);
			// Session session = Session.getDefaultInstance(props, null);
			session.setDebug(true);

			MimeMessage message = new MimeMessage(session);

			message.setSubject("网站回复");

			message.setContent(content, "text/plain");

			Address sendaddress = new InternetAddress(from);

			Address toAddress = new InternetAddress(to);

			message.setFrom(sendaddress);
			message.setRecipient(Message.RecipientType.TO, toAddress);

			message.saveChanges(); // implicit with send()

			Transport.send(message);
			// System.out.println("success!");
		} catch (MessagingException e) {
			System.out.println("send" + e.getMessage());
		}
	}

}

package com.email;

import javax.mail.Authenticator;

/**
 * @author Sech
 * 
 */
public class SmtpAuth extends Authenticator {
	private String user, password;

	public void setUserinfo(String getuser, String getpassword) {
		user = getuser;
		password = getpassword;
	}

	protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
		return new javax.mail.PasswordAuthentication(user, password);
	}

}

3.其他的就是直接在jsp页面中调用
SendEmail sendMail=new SendEmail();
sendMail.Send(content); 

就可以了.
注:这是我从下面的链接中学习并总结过来的.
参考链接: http://www.iteye.com/topic/71292?page=1

你可能感兴趣的:(jsp,qq,sun)