浏览 2343 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2010-04-09
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); } } 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |