Java发送邮件
来源:互联网 发布:南昌淘宝摄影招聘 编辑:程序博客网 时间:2024/06/05 05:02
TestController.java
import com.example.email.EmailSender;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import javax.annotation.Resource;import javax.servlet.http.HttpServletRequest;/** * @author Administrator * */@Controller@RequestMapping(value = "/")public class TestController { @Resource EmailSender emailSender; @RequestMapping(value = "/test") @ResponseBody public String test(HttpServletRequest request) { String subject = "「发送邮件测试」"; StringBuffer htmlEmailTemplate = new StringBuffer(); htmlEmailTemplate.append("<html>"); htmlEmailTemplate.append("<head>"); htmlEmailTemplate.append("<meta charset=\"utf-8\">"); htmlEmailTemplate.append("</head>"); htmlEmailTemplate.append("<body style=\"font-family:sans-serif;\">"); htmlEmailTemplate.append("<img src=\"").append("image/img/5.jpg").append("\" />"); htmlEmailTemplate.append("<br/>"); htmlEmailTemplate.append("你正在找回「xx」网站密码,请将以下资料填入对应位置以验证身份"); htmlEmailTemplate.append("<br/>"); htmlEmailTemplate.append("You are finding the password of xx website, please fill the below information to check your cridents."); htmlEmailTemplate.append("<br/>"); htmlEmailTemplate.append("<br/>"); htmlEmailTemplate.append("验证码 Verify Code:123456"); htmlEmailTemplate.append("</body>"); htmlEmailTemplate.append("</html>"); try { String serverPath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort(); emailSender.sendMail("test@test.com", subject, htmlEmailTemplate.toString(), serverPath); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } // 发送成功 return "success"; }}
EmailSender.java
import java.net.MalformedURLException;import java.net.URL;import java.net.UnknownHostException;import java.util.Properties;import org.apache.commons.mail.EmailException;import org.apache.commons.mail.ImageHtmlEmail;import org.apache.commons.mail.resolver.DataSourceUrlResolver;import org.springframework.stereotype.Component;import com.example.utils.ResourceUtils;import javax.mail.Address;import javax.mail.MessagingException;import javax.mail.Session;import javax.mail.Transport;import javax.mail.internet.AddressException;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeMessage;/** * @author Administrator * */@Componentpublic class EmailSender { private Properties prop = null; public EmailSender(){ prop = ResourceUtils.getEmailConfig(); }; public void sendMail(String toEmail,String subject,String htmlEmailTemplate, String serverPath) throws EmailException, MalformedURLException { ImageHtmlEmail email = new ImageHtmlEmail(); email.setHostName(prop.getProperty("mail.smtp.server")); email.setFrom(prop.getProperty("mail.smtp.useremail"), prop.getProperty("mail.smtp.name")); String auth = prop.getProperty("mail.smtp.auth"); if("true".equalsIgnoreCase(auth)){ email.setAuthentication(prop.getProperty("mail.smtp.username"), prop.getProperty("mail.smtp.password")); } email.setSmtpPort(Integer.valueOf(prop.getProperty("mail.smtp.port"))); email.addTo(toEmail); email.setCharset("UTF-8"); email.setSubject(subject); email.setHtmlMsg(htmlEmailTemplate); // set the alternative message //email.setTextMsg("Your email client does not support HTML messages"); URL url = new URL(serverPath); email.setDataSourceResolver(new DataSourceUrlResolver(url)); email.send(); } // 未测试 public static void send() throws Exception { ImageHtmlEmail email = new ImageHtmlEmail();// HtmlEmail email = new HtmlEmail(); email.setHostName("smtp.sina.com.cn");// email.setSmtpPort(110); email.setAuthentication("dgh8390@sina.com", "1388218286dg");// email.setSSLOnConnect(true);//开启SSL加密// email.setStartTLSEnabled(true);//开启TLS加密 email.setFrom("dgh8390@sina.com"); email.addTo("xxx@xxx.com"); email.setCharset("UTF-8"); email.setSubject("测试"); // 0 email.setHtmlMsg("这是测试内容<img src=\"http://www.apache.org/images/asf_logo_wide.gif\" />"); email.buildMimeMessage(); email.sendMimeMessage();// URL url = new URL("http://www.apache.org/images/asf_logo_wide.gif"); //1// email.setDataSourceResolver(new DataSourceUrlResolver(url));// email.setHtmlMsg("weeqweqwe");// //2// String cid = email.embed(url, "Apache logo");// email.setHtmlMsg("<html>The apache logo - <img src=\"cid:"+cid+"\"></html>");// email.setTextMsg("Y厕所生生世世事实上");// email.send(); } public static void send2() throws AddressException, MessagingException, UnknownHostException { // TODO Auto-generated method stub Properties props = new Properties();// props.put("mail.smtp.host", "mail.aishk.com"); props.put("mail.transport.protocol", "smtp");// props.put("mail.smtp.auth", "true"); Session session = Session.getDefaultInstance(props, null); MimeMessage msg = new MimeMessage(session); msg.setSubject("test-subject"); msg.setFrom(new InternetAddress("xxx@126.com"));// msg.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress("xxx@qq.com")); msg.setText("test content!"); msg.saveChanges(); Transport transport = session.getTransport(); transport.connect("smtp.126.com",25,"xiaomingusername", "xiaomingpassword"); Address[] addr = new Address[1]; addr[0] = new InternetAddress("xxx@qq.com"); transport.sendMessage(msg, addr); }}
ResourceUtils.java
import java.io.IOException;import java.io.InputStream;import java.net.URL;import java.util.Properties;import org.slf4j.Logger;import org.slf4j.LoggerFactory;/** * @author Administrator * */public class ResourceUtils { private static final Logger LOG = LoggerFactory.getLogger(ResourceUtils.class); private static final String EMAIL_CONFIG_FILE = "email.properties"; private ResourceUtils() { } public static Properties getEmailConfig() { return loadProperties(EMAIL_CONFIG_FILE); } private static Properties loadProperties(String propertiesFile) { Properties properties = new Properties(); ClassLoader cl = ResourceUtils.class.getClassLoader(); URL url = cl.getResource(EMAIL_CONFIG_FILE); try (InputStream in = url.openStream();) { properties.load(in); } catch (IOException e) { LOG.error("get email config file error: " + e, e); } return properties; }}
email.properties
#emailmail.smtp.protocol=smtpmail.smtp.server=smtp.sina.com.cnmail.smtp.port=25mail.smtp.auth=truemail.smtp.username=dgh8390@sina.commail.smtp.password=1388218286dgmail.smtp.useremail=dgh8390@sina.commail.smtp.name=HeiHeiHaHamail.smtp.timeout=25000
注意:需将SMTP服务开启
阅读全文
0 0
- [java]Java发送邮件
- java 邮件发送 --- 简单的邮件发送
- JAVA发送邮件及springboot发送邮件
- 用java发送邮件
- 用Java发送邮件
- java发送邮件源码
- java发送邮件
- Java发送邮件
- Java发送邮件程序
- java发送Email邮件
- 怎样用java发送邮件
- 利用java发送邮件
- java 邮件发送
- java邮件发送
- java邮件发送
- java定时发送邮件
- java发送邮件代码
- Java Mail 发送邮件
- 1.SPI总线学习
- Spring Boot应用的测试——Mockito
- 自然语言处理工具包jieba的使用
- 欢迎使用CSDN-markdown编辑器
- Spring框架总结——第二部分(基于xml配置+注解的方式配置IOC)
- Java发送邮件
- JavaScript DIV拖拽
- Error: java.io.IOException: Can't export data, please check failed map task logs
- 1030. Travel Plan (30)-PAT甲级真题
- 技术分享连载(五十一)
- 理解设计模式之策略模式
- Tensorflow 跑MaskRCNN框架遇到的各种坑(一)
- 反射用法
- 解决成功:安装SQl 2008为SQL Server代理服务提供的凭据无效