使用java程序发送邮件,下面jar肯定少不了我这里提供的下载地址为:
https://download.csdn.net/download/miwanmeng/10431482
把jar包下载后导入需要发送邮件的项目当中。
我这里使用的dome是QQ邮箱发送邮件的形式,这里需要说一下几点:
transport.connect("[email protected]", "xxxxx");
这里填写的是发送邮件的QQ邮箱和授权码,授权码获得方式可以打开QQ邮箱,设置--账户--POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务
这里点击开启、获取授权码就可以拿到。
还有就是不同邮箱163、QQ等等,他们的端口不一样要注意,具体端口号可以自行查询。这里是有的是QQ邮箱端口是465
下面就可以像下面dome一样开始发送邮件了
下面是我的代码dome
public static void main(String[] args) throws Exception {
InternetAddress[] internetAddress = new InternetAddress[] {
new InternetAddress("[email protected]")};
String tit="这是标题";
String content="这是内容部分";
Sessioc(internetAddress,tit,content);
}
/**
* 获取连接方法 Session
*
* @return
* @throws Exception
*/
public static void Sessioc(InternetAddress[] internetAddress,String tit,String content) throws Exception{
Properties properties = new Properties();
properties.put("mail.transport.protocol", "smtp");// 连接协议
properties.put("mail.smtp.host", "smtp.qq.com");// 主机名
properties.put("mail.smtp.port", 465);// 端口号
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.ssl.enable", "true");// 设置是否使用ssl安全连接 ---一般都使用
properties.put("mail.debug", "true");// 设置是否显示debug信息 true 会在控制台显示相关信息
// 得到回话对象
Session session = Session.getInstance(properties);
// 获取邮件对象
Message message = new MimeMessage(session);
// 设置发件人邮箱地址
message.setFrom(new InternetAddress("[email protected]"));
// 设置收件人邮箱地址
message.setRecipients(Message.RecipientType.TO,internetAddress);
// message.setRecipient(Message.RecipientType.TO, new
// InternetAddress("[email protected]"));//一个收件人
// 设置邮件标题
message.setSubject(tit);
// 设置邮件内容
message.setText(content);
// 得到邮差对象
Transport transport = session.getTransport();
// 连接自己的邮箱账户
transport.connect("[email protected]", "xxxxx");// 密码为QQ邮箱开通的stmp服务后得到的客户端授权码
// 发送邮件
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}