都快赶上每年一贴了,年年都有孩子们问我怎么在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(); } }