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("这是测试内容&lt;img src=\"http://www.apache.org/images/asf_logo_wide.gif\" /&gt;");        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服务开启
这里写图片描述

原创粉丝点击