1.添加jar包 html
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-email</artifactId> <version>1.5</version> </dependency>
2.發送代碼java
public class EmailUtils { /** * https://www.cnblogs.com/jimboi/p/6406237.html * 純文本內容郵件 */ public static void sendEmail(String emailSender,String emailSenderPassword,String subject,String emailReceiver,String content) throws EmailException { Email email = new SimpleEmail(); email.setHostName("smtp.qq.com"); //密碼是騰訊生成的第三方驗證碼 ascxdfbgztavbdlab email.setAuthentication(emailSender,emailSenderPassword); email.setFrom(emailSender); email.addTo(emailReceiver); email.setSubject(subject); //恭喜您註冊自媒體號審覈經過了,點擊以下連接登陸: <a href="http://www.baidu.com">xx電視臺自媒體登陸平臺</a> email.setContent(content,"text/html;charset=UTF-8"); email.send(); }
3.測試代碼
apache
public static void main(String[] args) { try { EmailUtils.sendEmail("123456@qq.com","ascxdfbgztavblab","審覈經過","654321@qq.com","恭喜您註冊自媒體號審覈經過了,點擊以下連接登陸: <a href=\"http://baidu,com">xx電視臺自媒體登陸平臺</a>"); } catch (EmailException e) { e.printStackTrace(); } }
4.如上去25端口發送郵件,在本地測試能夠經過。當打到線上環境時,發現報錯了。 服務器
後來經排查發現,咱們用的線上環境是阿里雲,阿里雲將 25端口封閉了。繼續查找資料,發現騰訊郵箱支持465端口,須要設置ssl。很少說,代碼以下。 session
public class EmailUtils { /** * https://www.cnblogs.com/jimboi/p/6406237.html * https://www.cnblogs.com/15ho/p/5891148.html * 純文本內容郵件 */ public static void sendEmail(EmailVO emailVO) throws EmailException, MessagingException { //設置ssl鏈接 Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; Properties props = System.getProperties(); props.setProperty("mail.smtp.host", "smtp.qq.com"); props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY); props.setProperty("mail.smtp.socketFactory.fallback", "false"); props.setProperty("mail.smtp.port", "465"); props.setProperty("mail.smtp.socketFactory.port", "465"); props.setProperty("mail.smtp.auth", "true"); //創建郵件會話 Session session = Session.getInstance(props, new Authenticator() { //身份認證 protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(emailVO.getEmailSender(),emailVO.getEmailSenderPassword()); } }); //創建郵件對象 MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(emailVO.getEmailSender())); message.setRecipients(Message.RecipientType.TO, emailVO.getEmailReceiver()); message.setSubject(emailVO.getSubject()); message.setContent(emailVO.getContent(),"text/html;charset=UTF-8"); //發送郵件 Transport.send(message); } }
注意:如上郵箱服務器是採用騰訊的。因此發件人必須是騰訊的郵箱。 socket
ps:今天遇到個問題,我用的騰訊的郵箱服務器,帳號+受權碼採用 網易的,發送郵件始終報535:認證失敗。後來才知道郵箱服務器認證只能認證本身家的帳號。ide