Java Web 发送邮件示例

一、Maven 添加依赖坐标

这个示例基于使用Maven 搭建的Web项目,在导入依赖Jar包时,只需在项目的pom.xml配置文件中,写入下面的依赖坐标即可:

<!--邮件发送依赖-->
    <dependency>
      <groupId>com.sun.mail</groupId>
      <artifactId>javax.mail</artifactId>
      <version>1.6.2</version>
    </dependency>

 二、创建邮件发送工具类

在项目的Utils包下,新建SendEmail类,具体内容如下:

package cn.imyjs.utils;

import com.sun.mail.util.MailSSLSocketFactory;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.GeneralSecurityException;
import java.util.Properties;

/**
 * 发送邮件提醒工具类
 */
public class SendEmailUtil {
    public static String sentEmail(String ipaddr, String message) throws MessagingException, GeneralSecurityException {

        //创建一个配置文件并保存
        Properties properties = new Properties();
        properties.setProperty("mail.host","smtp.qq.com");
        properties.setProperty("mail.transport.protocol","smtp");
        properties.setProperty("mail.smtp.auth","true");

        //QQ存在一个特性设置SSL加密
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        properties.put("mail.smtp.ssl.enable", "true");
        properties.put("mail.smtp.ssl.socketFactory", sf);

        //创建一个session对象
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("192550858@qq.com","在QQ邮箱获取的授权码");
            }
        });

        //开启debug模式
        session.setDebug(true);

        //获取连接对象
        Transport transport = session.getTransport();

        //连接服务器
        transport.connect("smtp.qq.com","192550858@qq.com","在QQ邮箱获取的授权码");

        //创建邮件对象
        MimeMessage mimeMessage = new MimeMessage(session);

        //邮件发送人
        mimeMessage.setFrom(new InternetAddress("192550858@qq.com"));

        //邮件接收人
        mimeMessage.setRecipient(Message.RecipientType.TO,new InternetAddress("2410685763@qq.com"));

        //邮件标题
        mimeMessage.setSubject("任务墙提醒");

        //邮件内容
        mimeMessage.setContent("收到来自IP地址:" + ipaddr + "的提醒信息:\n" + message,"text/html;charset=UTF-8");

        //发送邮件
        transport.sendMessage(mimeMessage,mimeMessage.getAllRecipients());

        //关闭连接
        transport.close();

        return "success";
    }


}

 三、功能测试

然后就可以编写测试代码,测试邮件发送了,具体如下:

    @Test
    public void testSendEmail() throws MessagingException, GeneralSecurityException {
        String s = SendEmailUtil.sentEmail("127.0.0.1","测试发送邮件提醒信息!");
        System.out.println(s);

    }

 

四、微信关注

                   编程那点事儿

 

 

阅读剩余
THE END