javaWeb之邮箱发送(邮箱客户端配置)

这里使用的是本机的邮箱服务器  ,

代码执行条件:

1.·邮箱服务器  , 下载地址   密码   s4xn    

    

邮箱服务器配置:

 1):安装 

 2):打开服务器  

       

红色部分是默认账号,不用处理

3)系统设置  》点击工具  》服务器设置》

  

 

      4)创建账号

                       

 

    

2 .邮箱客户端   ,可以到官网上下载:

  

1.邮箱客户端的安装

接收和发送邮件服务器:  localhost

3 .mail.jar  包

4.Util工具类

package com.study.mail;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;

public class MailUtils {
       // email :email 地址 ,subject  邮箱主题,emailMsg 邮箱信息
    public static void sendMail(String email,String subject, String emailMsg)
            throws AddressException, MessagingException {
        // 1.创建一个程序与邮件服务器会话对象 Session
        
        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", "SMTP");//发送邮件的协议
        props.setProperty("mail.host", "localhost");//发送邮件的服务器地址
        props.setProperty("mail.smtp.auth", "true");// 指定验证为true

        // 创建验证器
        Authenticator auth = new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("tom", "123456");//发送邮件的账号认证
            }
        };

        Session session = Session.getInstance(props, auth);

        // 2.创建一个Message,它相当于是邮件内容
        Message message = new MimeMessage(session);

        message.setFrom(new InternetAddress("tom@study.com")); // 设置发送者

        message.setRecipient(RecipientType.TO, new InternetAddress(email)); // 设置发送方式与接收者

        message.setSubject(subject);//设置邮件的主题
        // message.setText("这是一封激活邮件,请<a href='#'>点击</a>");
        //设置邮件的内容
        message.setContent(emailMsg, "text/html;charset=utf-8");
        
        // 3.创建 Transport用于将邮件发送

        Transport.send(message);
    }
}

 测试类:

package com.study.mail;

import javax.mail.MessagingException;
import javax.mail.internet.AddressException;

public class sendMailTest {

    public static void main(String[] args) throws AddressException, MessagingException {
        MailUtils.sendMail("lucy@study.com","测试邮件","这是一封测试邮件");
    }

}



原文地址:https://www.cnblogs.com/shaoxiaohuan/p/7827696.html