[java]代码库
import org.springframework.stereotype.Component;
import com.sun.mail.util.MailSSLSocketFactory;
import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.GeneralSecurityException;
import java.util.Properties;
@Component
public class MailManager {
//发送邮件
public static void sendMail(String email, String emailMsg)
throws AddressException, MessagingException, GeneralSecurityException {
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
// 1.创建一个程序与邮件服务器会话对象 Session
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "SMTP");
// props.setProperty("mail.smtp.host", "smtp.163.com");
props.setProperty("mail.smtp.host", "smtp.qq.com");
props.setProperty("mail.smtp.port", "465");
// 指定验证为true
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.smtp.timeout","2000");
props.put("mail.smtp.ssl.enable", true);
props.put("mail.smtp.ssl.socketFactory", sf);
// 验证账号及密码,密码需要是第三方授权码
Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("895771726@qq.com", "****");
}
};
Session session = Session.getInstance(props, auth);
// 2.创建一个Message,它相当于是邮件内容
Message message = new MimeMessage(session);
// 设置发送者
message.setFrom(new InternetAddress("895771726@qq.com"));
// 设置发送方式与接收者
message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(email));
// 设置主题
message.setSubject("love");
// 设置内容
message.setContent(emailMsg, "text/html;charset=utf-8");
// 3.创建 Transport用于将邮件发送
Transport.send(message);
}
public static void main(String[] args) throws AddressException, MessagingException, GeneralSecurityException {
String emailMsg = "验证码:658219";
sendMail("895771726@qq.com", emailMsg);
// sendMail("89577126@qq.com", emailMsg);
}
}
by: 发表于:2018-05-24 10:41:04 顶(0) | 踩(0) 回复
??
回复评论