package com.shareinfo.common.util.mail;
import java.util.Calendar;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class MailUtil {
@SuppressWarnings("static-access")
public static void sendMessage(String smtpHost, String from,
String fromUserPassword, String to, String subject,
String messageText, String messageType) throws MessagingException {
// 第一步:配置javax.mail.Session对象
System.out.println("为" + smtpHost + "配置mail session对象");
Properties props = new Properties();
props.put("mail.smtp.host", smtpHost);
props.put("mail.smtp.starttls.enable","true");//使用 STARTTLS安全连接
props.put("mail.smtp.ssl.enable", "true");//QQ邮箱的SSL加密
//props.put("mail.smtp.port", "25"); //google使用465或587端口
props.put("mail.smtp.auth", "true"); // 使用验证
//props.put("mail.debug", "true");
Session mailSession = Session.getInstance(props,new MyAuthenticator(from,fromUserPassword));
// 第二步:编写消息
System.out.println("编写消息from——to:" + from + "——" + to);
InternetAddress fromAddress = new InternetAddress(from);
InternetAddress toAddress = new InternetAddress(to);
MimeMessage message = new MimeMessage(mailSession);
message.setFrom(fromAddress);
message.addRecipient(RecipientType.TO, toAddress);
message.setSentDate(Calendar.getInstance().getTime());
message.setSubject(subject);
message.setContent(messageText, messageType);
// 第三步:发送消息
Transport transport = mailSession.getTransport("smtp");
transport.connect(smtpHost,"893947024", fromUserPassword);
transport.send(message, message.getRecipients(RecipientType.TO));
System.out.println("message yes");
}
public static void main(String[] args) {
try {
/*MailUtil.sendMessage("smtp.qq.com", "458909264@qq.com",
"GUOQIANG12345678", "guoqiang@share-all.com.cn", "nihao",
"---------------wrwe-----------",
"text/html;charset=gb2312");*/
MailUtil.sendMessage("smtp.qq.com", "893947024@qq.com",
"hcsnwzcwqvgvbfbe", "lishengchen@share-all.com.cn", "nihao",
"---------------wrwe-----------",
"text/html;charset=gb2312"); //hcsnwzcwqvgvbfbe 16位的授权码
} catch (Exception e) {
e.printStackTrace();
}
}
}
class MyAuthenticator extends Authenticator{
String userName="";
String password="";
public MyAuthenticator(){
}
public MyAuthenticator(String userName,String password){
this.userName=userName;
this.password=password;
}
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(userName, password);
}
}
用javamail发送邮件
最新推荐文章于 2025-03-13 15:37:54 发布
本文详细介绍了一个使用Java实现的邮件发送实用类,通过配置SMTP主机、端口、用户名及密码,利用MIME消息格式,实现从指定发件人向收件人发送带有主题和正文的HTML格式邮件的过程。文章提供了完整的代码示例,展示了如何创建邮件会话、编写并发送邮件。
467

被折叠的 条评论
为什么被折叠?



