使用環境
準備工作
- 使用maven將spring、mybatis、mysql、java mail所需要的包導入,具體導入的包見demo的pom.xml
- 申請一個郵箱賬號(若有則跳過)
- 對於qq郵箱,需要申請授權碼,路徑:設置->賬戶->POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服務->開啓POP3/SMTP服務
- 在mysql中新建表user,並將想要發送的郵箱參數填入,表格式如下
id name
基礎配置
spring、mybatis
詳細配置見demo
java mail
使用@PropertySource和@Value將mail.properties的內容讀取出來。
@Configuration @PropertySource("mail.properties") public class MailConfig { @Value("${mail.host}") private String mailHost; @Value("${mail.port}") private int mailPort; @Value("${mail.username}") private String username; @Value("${mail.password}") private String password; @Value("${mail.auth}") private String auth; @Value("${mail.timeout}") private String time0ut; @Value("${mail.starttls.enable}") private String starttlsEnable; @Value("${mail.socketFactory.fallback}") private String socketFactoryFallback; @Value("${mail.socketFactory.class}") private String socketFactoryClass; ......
將上面讀取的內容添加到mailsender中進行配置
@Bean public MailSender mailSender(Environment env){ JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); mailSender.setHost(mailHost); mailSender.setPort(Integer.valueOf(mailPort)); mailSender.setUsername(username); mailSender.setPassword(password); mailSender.setDefaultEncoding("utf-8"); Properties jpro = new Properties(); jpro.setProperty("mail.smtp.auth", auth); jpro.setProperty("mail.smtp.timeout", time0ut); jpro.setProperty("mail.smtp.starttls.enable", starttlsEnable); jpro.setProperty("mail.smtp.socketFactory.port", String.valueOf(mailPort)); jpro.setProperty("mail.smtp.socketFactory.fallback", socketFactoryFallback); jpro.setProperty("mail.smtp.socketFactory.class", socketFactoryClass); mailSender.setJavaMailProperties(jpro); return mailSender; }
這樣java mail的基礎配置就基本完成
發送郵件
目標是發送基於html的郵件,這樣我們可以定製出各種各樣的新鮮樣式
讀取html文件
爲了方便筆者直接使用了apache的commons-io讀取文件內容String text = ""; File file = ResourceUtils.getFile("classpath:mail.html"); text = FileUtils.readFileToString(file, "utf-8");
讀取數據庫用戶列表
使用mybatis讀取mysql中的email列表實現羣發功能,具體操作見demo
創建郵件
郵件至少由4個部分組成,分別是發送者,接受者,郵件名稱,內容,可用以下參數配置MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true, "utf-8"); helper.setFrom(mailUserName); helper.setTo(email); helper.setSubject("DEMO"); helper.setText(text, true); //true可以顯示html格式的文本
- 發送郵件
最後使用mailSender.send(message);
發送郵件即可。
源碼下載
- csdn: http://download.csdn.net/detail/will4906/9880292
- github: https://github.com/will4906/MailGroup
讚賞
讚賞 | |
微信 | 支付寶 |