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

使用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);
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值