java ssl发送邮件_Java Mail 发送邮件(SSL加密方式,TSL加密方式)

一、一般配置

发送邮件需要用到  mail包 maven 依赖如下:

1

2

3 javax.mail

4 mail

5 1.4

6

SSL加密方式需要用到MailSSLSocketFactory类

com.sun.mail

javax.mail

1.4.4

获取配置文件:

1 //获取邮箱发送邮件的配置信息

2 publicProperties getEmailProperties(){3 Properties props = newProperties();4 String host = evn.getProperty("email.host");5 String protocol = evn.getProperty("email.protocol");6 String port = evn.getProperty("email.port");7 String from = evn.getProperty("email.from");8 String pwd = evn.getProperty("email.password");9 props.put("mail.smtp.host", host);//设置服务器地址

10 props.put("mail.store.protocol" , protocol);//设置协议

11 props.put("mail.smtp.port", port);//设置端口

12 props.put("from", from);13 props.put("pwd", pwd);14 props.put("mail.smtp.auth" , "true");15 returnprops;16 }

邮件发送代码类:

1 /**

2 *

3 * @file springBootExample.example.infrastructure4 *5 */

6 packagecom.tyky.educloud.platform.util;7

8 /**

9 * @ClassName: SendEmail10 * @Description: TODO(这里用一句话描述这个类的作用)11 *@authorhoojjack12 * @date 2017年7月19日 下午3:23:4213 *14 */

15 importjava.util.Date;16 importjava.util.Properties;17

18 importjavax.mail.Authenticator;19 importjavax.mail.Message;20 importjavax.mail.MessagingException;21 importjavax.mail.PasswordAuthentication;22 importjavax.mail.Session;23 importjavax.mail.Transport;24 importjavax.mail.internet.AddressException;25 importjavax.mail.internet.InternetAddress;26 importjavax.mail.internet.MimeMessage;27

28 public classSendEmail {29

30 public static Properties props = newProperties();31

32 public static voidsetProps(Properties props) {33 SendEmail.props =props;34 }35

36 public staticProperties getProps() {37 returnprops;38 }39

40 /**

41 * 获取Session42 *43 *@return

44 */

45 private static Session getSession(final String from, finalString pwd) {46

47 Authenticator authenticator = newAuthenticator() {48

49 @Override50 protectedPasswordAuthentication getPasswordAuthentication() {51 return newPasswordAuthentication(from, pwd);52 }53

54 };55 Session session =Session.getDefaultInstance(props, authenticator);56

57 returnsession;58 }59

60 public static void send(String content, String toEmail) throwsAddressException, MessagingException {61 Properties properties =getProps();62 String from = properties.getProperty("from");63 String pwd = properties.getProperty("pwd");64 String subject = properties.getProperty("subject");65

66 if (null == from || null ==pwd) {67 System.out.println("发送邮箱为空");68 return;69 }70 if (null ==subject) {71 subject = "平台";72 }73 Session session =getSession(from, pwd);74 //Instantiate a message

75 Message msg = newMimeMessage(session);76 //Set message attributes

77 msg.setFrom(newInternetAddress(from));78 InternetAddress[] address = { newInternetAddress(toEmail) };79 msg.setRecipients(Message.RecipientType.TO, address);80 msg.setSubject(subject);81 msg.setSentDate(newDate());82 msg.setContent(content, "text/html;charset=utf-8");83 //Send the message

84 Transport.send(msg);85 }86

87 public staticString generateContent(String contentTitle, String url, String username, String email,88 String validateCode) {89

90 //String validataCode = MD5Util.encode2hex(email);

91

92 /// 邮件的内容

93 StringBuffer sb = newStringBuffer(contentTitle);94 sb.append("" + url + "?username=");101 sb.append(username);102 sb.append("&email=");103 sb.append(email);104 sb.append("&validateCode=");105 sb.append(validateCode);106 sb.append("");107 returnsb.toString();108 }109

110 }

邮件发送完整的代码:

1 /**

2 * @ClassName: SendEmail3 * @Description: TODO(这里用一句话描述这个类的作用)4 *@authorhoojjack5 * @date 2017年7月19日 下午3:23:426 *7 */

8 importjava.util.Date;9 importjava.util.Properties;10

11 importjavax.mail.Authenticator;12 importjavax.mail.Message;13 importjavax.mail.MessagingException;14 importjavax.mail.PasswordAuthentication;15 importjavax.mail.Session;16 importjavax.mail.Transport;17 importjavax.mail.internet.AddressException;18 importjavax.mail.internet.InternetAddress;19 importjavax.mail.internet.MimeMessage;20

21 public classSendEmail {22

23 public static Properties props = newProperties();24

25 public static voidsetProps(Properties props) {26 SendEmail.props =props;27 }28

29 public staticProperties getProps() {30 props.put("mail.smtp.host", "smtp.163.com");//设置服务器地址

31 props.put("mail.store.protocol", "smtp.163.com");//设置协议

32 props.put("mail.smtp.port", 25);//设置端口

33 props.put("from", "XXX");34 props.put("pwd", "XXX");35 props.put("mail.smtp.auth", "true");36 }37

38 /**

39 * 获取Session40 *41 *@return

42 */

43 private static Session getSession(final String from, finalString pwd) {44

45 Authenticator authenticator = newAuthenticator() {46

47 @Override48 protectedPasswordAuthentication getPasswordAuthentication() {49 return newPasswordAuthentication(from, pwd);50 }51

52 };53 Session session =Session.getDefaultInstance(props, authenticator);54

55 returnsession;56 }57

58 public static void send(String content, String toEmail) throwsAddressException, MessagingException {59 Properties properties =getProps();60 String from = properties.getProperty("from");61 String pwd = properties.getProperty("pwd");62 String subject = properties.getProperty("subject");63

64 if (null == from || null ==pwd) {65 System.out.println("发送邮箱为空");66 return;67 }68 if (null ==subject) {69 subject = "平台";70 }71 Session session =getSession(from, pwd);72 //Instantiate a message

73 Message msg = newMimeMessage(session);74 //Set message attributes

75 msg.setFrom(newInternetAddress(from));76 InternetAddress[] address = { newInternetAddress(toEmail) };77 msg.setRecipients(Message.RecipientType.TO, address);78 msg.setSubject(subject);79 msg.setSentDate(newDate());80 msg.setContent(content, "text/html;charset=utf-8");81 //Send the message

82 Transport.send(msg);83 }84

85 public staticString generateContent(String contentTitle, String url, String username, String email,86 String validateCode) {87

88 //String validataCode = MD5Util.encode2hex(email);

89

90 /// 邮件的内容

91 StringBuffer sb = newStringBuffer(contentTitle);92 sb.append("" + url + "?username=");99 sb.append(username);100 sb.append("&email=");101 sb.append(email);102 sb.append("&validateCode=");103 sb.append(validateCode);104 sb.append("");105 returnsb.toString();106 }107

108 }

以下是两种不同加密方式的代码,与上面默认25端口的方式差别较小,注意不同加密方式红色部分。

1. JavaMail – via TLS

1 packagecom.mkyong.common;2

3 importjava.util.Properties;4

5 importjavax.mail.Message;6 importjavax.mail.MessagingException;7 importjavax.mail.PasswordAuthentication;8 importjavax.mail.Session;9 importjavax.mail.Transport;10 importjavax.mail.internet.InternetAddress;11 importjavax.mail.internet.MimeMessage;12

13 public classSendMailTLS {14

15 public static voidmain(String[] args) {16

17 final String username = "[email protected]";18 final String password = "password";19

20 Properties props = newProperties();21 props.put("mail.smtp.auth", "true");22 props.put("mail.smtp.starttls.enable", "true");23 props.put("mail.smtp.host", "smtp.gmail.com");24 props.put("mail.smtp.port", "587");25

26 Session session =Session.getInstance(props,27 newjavax.mail.Authenticator() {28 protectedPasswordAuthentication getPasswordAuthentication() {29 return newPasswordAuthentication(username, password);30 }31 });32

33 try{34 Message message = newMimeMessage(session);35 message.setFrom(new InternetAddress("[email protected]"));36 message.setRecipients(Message.RecipientType.TO,37 InternetAddress.parse("[email protected]"));38 message.setSubject("Testing Subject");39 message.setText("Dear Mail Crawler,"

40 + "\n\n No spam to my email, please!");41

42 Transport.send(message);43 System.out.println("Done");44

45 } catch(MessagingException e) {46 throw newRuntimeException(e);47 }48 }49 }

2. JavaMail – via SSL

packagecom.mkyong.common;importjava.util.Properties;importjavax.mail.Message;importjavax.mail.MessagingException;importjavax.mail.PasswordAuthentication;importjavax.mail.Session;importjavax.mail.Transport;importjavax.mail.internet.InternetAddress;importjavax.mail.internet.MimeMessage;public classSendMailSSL {public static voidmain(String[] args) {

Properties props= newProperties();

props.put("mail.smtp.host", "smtp.gmail.com");

props.put("mail.smtp.socketFactory.port", "465");

props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

props.put("mail.smtp.auth", "true");

props.put("mail.smtp.port", "465");

Session session=Session.getDefaultInstance(props,newjavax.mail.Authenticator() {protectedPasswordAuthentication getPasswordAuthentication() {return new PasswordAuthentication("username","password");

}

});try{

Message message= newMimeMessage(session);

message.setFrom(new InternetAddress("[email protected]"));

message.setRecipients(Message.RecipientType.TO,

InternetAddress.parse("[email protected]"));

message.setSubject("Testing Subject");

message.setText("Dear Mail Crawler," +

"\n\n No spam to my email, please!");

Transport.send(message);

System.out.println("Done");

}catch(MessagingException e) {throw newRuntimeException(e);

}

}

}

注意:如果以上ssl不行可以尝试将ssl红色部分用以下代码替换:

1 MailSSLSocketFactory sf = null;2 try{3 sf = newMailSSLSocketFactory();4 sf.setTrustAllHosts(true);5 } catch(GeneralSecurityException e1) {6 e1.printStackTrace();7 }8 props.put("mail.smtp.ssl.enable", "true");9 props.put("mail.smtp.ssl.socketFactory", sf);

你可能感兴趣的:(java,ssl发送邮件)