1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
| import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Component;
import javax.mail.internet.MimeMessage; import java.io.BufferedReader; import java.io.FileReader;
@Component public class MailUtil { private static JavaMailSender javaMailSender; private static String host = "smtp.qq.com"; private static String emailFrom; private static Integer SMTPPort = 465; private static String coding = "utf-8"; private static String password;
private static void initJavaMailSender() throws Exception { if(javaMailSender == null) { synchronized (MailUtil.class){ if(javaMailSender == null){ JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); FileReader fileReader = new FileReader("filename"); BufferedReader bufferedReader = new BufferedReader(fileReader); emailFrom = bufferedReader.readLine(); password = bufferedReader.readLine();
mailSender.setHost(host); mailSender.setPort(SMTPPort); mailSender.setUsername(emailFrom); mailSender.setPassword(password);
Properties javaMailProperties = new Properties(); javaMailProperties.put("mail.smtp.auth", true); javaMailProperties.put("mail.smtp.starttls.enable", true); javaMailProperties.put("mail.smtp.starttls.required", true); javaMailProperties.put("mail.smtp.timeout", 5000); javaMailProperties.put("mail.smtp.ssl.enable",true); javaMailProperties.put("mail.smtp.socketFactory.class",javax.net.ssl.SSLSocketFactory.class);
mailSender.setDefaultEncoding(coding); mailSender.setJavaMailProperties(javaMailProperties);
javaMailSender = mailSender; } } } }
public void sendMessage(String toEmail, String code) throws Exception{ initJavaMailSender(); MimeMessage message = javaMailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message,true); helper.setFrom(emailFrom); helper.setTo(toEmail); helper.setSubject("主题");
helper.setText("内容", false); helper.setText("HTML", true);
javaMailSender.send(message); }
}
|