论坛首页 入门技术论坛

使用javamail通过需要身份验证的smtp服务器发送邮件

浏览 2343 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2010-04-09  
使用javamail发送邮件时,如果smtp服务器需要身份验证,我们需要继承
javax.mail.Authenticator自己实现一个类,该类覆盖getPasswordAuthentication()
方法,返回一个包含用户名、口令信息的PasswordAuthentication,然后
在获取Session时指定这个我们自己实现的类。同时我们还需要指定"mail.smtp.auth"
属性为"true"。以下是示例代码:

发送邮件的类如下:
import java.util.Properties;

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

public class MessageSender {
	protected String to = null;
	protected String server = null;
	protected String user = null;
	protected String password = null;
	
	public MessageSender(String to, String server, String user, String password) {
		this.to = to;
		this.server = server;
		this.user = user;
		this.password = password;
	}
	
	public void send(String content) throws AddressException, MessagingException {
		Properties props = new Properties();
		props.put("mail.smtp.host", server);
		props.put("mail.smtp.auth", "true");

	    Session session = Session.getInstance(props, new MyAuthenticator(user, password));
	    
	    Message msg = new MimeMessage(session);

	    msg.setRecipients(Message.RecipientType.TO,  InternetAddress.parse(to));

	    msg.setSubject("test");
		msg.setText(content);

	    Transport.send(msg);
	}
}


继承Authenticator自己实现的类如下:

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;

public class MyAuthenticator extends Authenticator {
	protected String id = "";
	protected String password = "";
	
	public MyAuthenticator(String id, String password) {
		this.id = id;
		this.password = password;
	}
	
	protected PasswordAuthentication getPasswordAuthentication() {
		return new PasswordAuthentication(id, password);
	}
}

论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics