都快趕上每年一貼了,年年都有孩子們問我怎麼在java程式裡面發郵件,特別是html格式的郵件,在這裡貼個例子吧:
maven裡面引入javamail
<dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4.7</version> </dependency>
然後寫個簡單的工具類
package com.xxx.tools;import javax.mail.MessagingException;import javax.mail.Session;import javax.mail.Transport;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeMessage;import javax.mail.internet.MimeUtility;public class HtmlEmail { private String smtpServer; private String username; private String password; public void sendMessage(String to, String subject, String messageText) throws MessagingException, java.io.UnsupportedEncodingException { java.util.Properties props = new java.util.Properties(); props.setProperty("mail.smtp.auth", "true");//指定是否需要SMTP驗證 props.setProperty("mail.smtp.host", smtpServer);//指定SMTP伺服器 props.put("mail.transport.protocol", "smtp"); Session mailSession = Session.getDefaultInstance(props); //mailSession.setDebug(true);//是否在控制台顯示debug資訊 InternetAddress fromAddress = new InternetAddress(username); InternetAddress toAddress = new InternetAddress(to); MimeMessage emailMessage = new MimeMessage(mailSession); emailMessage.setFrom(fromAddress); emailMessage.addRecipient(javax.mail.Message.RecipientType.TO, toAddress); emailMessage.setSentDate(new java.util.Date()); emailMessage.setSubject(MimeUtility.encodeText(subject, "utf-8", "B")); emailMessage.setContent(messageText, "text/html;charset=utf-8"); Transport transport = mailSession.getTransport("smtp"); transport.connect(smtpServer, username, password); transport.sendMessage(emailMessage, emailMessage.getAllRecipients()); transport.close(); } public String getSmtpServer() { return smtpServer; } public void setSmtpServer(String smtpServer) { this.smtpServer = smtpServer; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; }}
然後在spring裡面配置一下
<bean id="htmlMail" class="com.xxx.tools.HtmlEmail"> <property name="smtpServer" value="smtp.qq.com"/> <property name="username" value="1xxxx7@qq.com"></property> <property name="password" value="xxxxxxx"></property> </bean>
然後在需要使用的地方使用:
@Controller@RequestMapping("/user")public class UserRegController { @Resource private HtmlEmail email; @RequestMapping("/reg") public void sendMail(@RequestParam("username") String username, @RequestParam("userpass") String userpass, @RequestParam("email") String email_addr, HttpServletRequest request) { String valid_string = request.getSession(true).getId(); String valid_url = "<a href='http://localhost:8080/user/valid?username=" + username + "&validString=" + valid_string + "' target='_blank'> 點擊此連結啟用帳號</a>"; try { email.sendMessage(email_addr, "使用者啟用", valid_url); } catch (MessagingException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } }