java实现邮件发送原生

Java实现邮件发送
一、邮件服务器与传输协议
要在网络上实现邮件功能,必须要有专门的邮件服务器。这些邮件服务器类似于现实生活中的邮局,它主要负责接收用户投递过来的邮件,并把邮件投递到邮件接收者的电子邮箱中。

SMTP服务器地址:一般是 smtp.xxx.com,比如163邮箱是smtp.163.com,qq邮箱是smtp.qq.com。

SMTP协议

通常把处理用户smtp请求(邮件发送请求)的服务器称之为SMTP服务器(邮件发送服务器)。

POP3协议

通常把处理用户pop3请求(邮件接收请求)的服务器称之为POP3服务器(邮件接收服务器)。

二、Java发送邮件
在这里插入图片描述
在这里插入图片描述
使用到的jar包:

mail.jar
activation.jar
QQ邮箱需获取相应的权限:

QQ邮箱–>邮箱设置–>账户–>POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务 开启POP3/SMTP服务,然后获取16位授权码(注意不要将授权码泄露,一个账户可以拥有多个授权码)
在这里插入图片描述
Java实现纯文本邮件发送

public class SendEmail {


    public static void sendRegisterEmail(String username,String code,String email){

        try {
            //创建一个配置文件并保存
            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("1070xxxx@qq.com", "邮箱的授权码oubfff");
                }
            });
            //开启debug模式
            session.setDebug(true);
            //获取连接对象
            Transport transport = session.getTransport();
            //连接服务器
            //配置发送人右键的账号和授权码
            transport.connect("smtp.qq.com", "1070xxxx@qq.com", "邮箱的授权码oubfff");

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

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

            //邮件接收人
            mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(email));


            String content="<a href='http://localhost:8080/baby/activationServlet?username="+username+"&code="+code+"'>点击激活哦</a>";

            //邮件标题
            mimeMessage.setSubject("注册激活邮件");


            //邮件内容
            mimeMessage.setContent(content, "text/html;charset=gbk");

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

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

        }catch (Exception e){
            e.printStackTrace();
            throw  new RuntimeException("发送注册邮件是失败!");
        }
    } }

Java实现文本图片附件复杂的邮件发送
MIME(多用途互联网邮件扩展类型)

MimeBodyPart类

javax.mail.internet.MimeBodyPart类 表示的是一个MIME消息,它和MimeMessage类一样都是从Part接口继承过来。

MimeMultipart类

javax.mail.internet.MimeMultipart是抽象类 Multipart的实现子类,它用来组合多个MIME消息。一个MimeMultipart对象可以包含多个代表MIME消息的MimeBodyPart对象

public class SendComplexEmail {
    public static void main(String[] args) throws GeneralSecurityException, MessagingException {
        Properties prop = new Properties();
        prop.setProperty("mail.host", "smtp.qq.com");  设置QQ邮件服务器
        prop.setProperty("mail.transport.protocol", "smtp"); // 邮件发送协议
        prop.setProperty("mail.smtp.auth", "true"); // 需要验证用户名密码

        // QQ邮箱设置SSL加密
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        prop.put("mail.smtp.ssl.enable", "true");
        prop.put("mail.smtp.ssl.socketFactory", sf);

        //1、创建定义整个应用程序所需的环境信息的 Session 对象
        Session session = Session.getDefaultInstance(prop, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                //传入发件人的姓名和授权码
                return new PasswordAuthentication("61904@qq.com","16位授权码");
            }
        });

        //2、通过session获取transport对象
        Transport transport = session.getTransport();

        //3、通过transport对象邮箱用户名和授权码连接邮箱服务器
        transport.connect("smtp.qq.com","61904@qq.com","16位授权码");

        //4、创建邮件,传入session对象
        MimeMessage mimeMessage = complexEmail(session);

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

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


    }

    public static MimeMessage complexEmail(Session session) throws MessagingException {
        //消息的固定信息
        MimeMessage mimeMessage = new MimeMessage(session);

        //发件人
        mimeMessage.setFrom(new InternetAddress("619017@qq.com"));
        //收件人
        mimeMessage.setRecipient(Message.RecipientType.TO,new InternetAddress("619017@qq.com"));
        //邮件标题
        mimeMessage.setSubject("带图片和附件的邮件");

        //邮件内容
        //准备图片数据
        MimeBodyPart image = new MimeBodyPart();
        DataHandler handler = new DataHandler(new FileDataSource("E:\\IdeaProjects\\WebEmail\\resources\\测试图片.png"));
        image.setDataHandler(handler);
        image.setContentID("test.png"); //设置图片id

        //准备文本
        MimeBodyPart text = new MimeBodyPart();
        text.setContent("这是一段文本<img src='cid:test.png'>","text/html;charset=utf-8");

        //附件
        MimeBodyPart appendix = new MimeBodyPart();
        appendix.setDataHandler(new DataHandler(new FileDataSource("E:\\IdeaProjects\\WebEmail\\resources\\测试文件.txt")));
        appendix.setFileName("test.txt");

        //拼装邮件正文
        MimeMultipart mimeMultipart = new MimeMultipart();
        mimeMultipart.addBodyPart(image);
        mimeMultipart.addBodyPart(text);
        mimeMultipart.setSubType("related");//文本和图片内嵌成功

        //将拼装好的正文内容设置为主体
        MimeBodyPart contentText = new MimeBodyPart();
        contentText.setContent(mimeMultipart);

        //拼接附件
        MimeMultipart allFile = new MimeMultipart();
        allFile.addBodyPart(appendix);//附件
        allFile.addBodyPart(contentText);//正文
        allFile.setSubType("mixed"); //正文和附件都存在邮件中,所有类型设置为mixed


        //放到Message消息中
        mimeMessage.setContent(allFile);
        mimeMessage.saveChanges();//保存修改

        return mimeMessage;
    } }

JavaWeb发送邮件(网站注册成功发送提示邮件)
在这里插入图片描述
JavaWeb发送邮件(网站注册成功发送提示邮件)
在数据库和pojo里面定义一个 mail 和 status来表示激活状态
1.User

public class User {

	private Long id;
	private String username;
	private String password;
	private String salt;
	private String email;
	private Date last_login_time;
	private Date created;
	private Integer status;
	private String code;

2.dao…
在这里插入图片描述

3.service

public interface UserService {

	/**
	   *      登录
	 * @param username
	 * @param password
	 * @return
	 */
	public User login(String username,String password)throws CustomerException;
	
	/**
	 *  注册
	 * @param user
	 */
	public void register(User user)throws CustomerException;


	/**
	 * 激活账户
	 * @param username
	 * @param code
	 * @return
	 */
	public void activation(String username,String code) throws CustomerException;

}

注册逻辑service

public class UserServiceImpl implements UserService {

	private UserDao userDao = new UserDaoImpl();

	@Override
	public void register(User user) throws CustomerException {

		// 1.判空
		if (user == null) {
			throw new CustomerException("用户数据为空!");
		}
		if (user.getUsername() == null || user.getUsername().trim().equals("")) {
			throw new CustomerException("用户名为空!");
		}
		// 密码 邮箱

		// 2.判断用户名是否使用
		if (userDao.findUserByUsername(user.getUsername()) != null) {
			throw new CustomerException("用户名已经使用!");
		}

		// 3.判断邮箱是否使用
		if (userDao.findUserByEmail(user.getEmail()) != null) {
			throw new CustomerException("邮箱已经使用!");
		}


		//4.获取盐
		String salt = Md5Utils.createSalt();
		
		
		
		//5.密码加密
		String md5Password = Md5Utils.md5Password(user.getPassword(), salt);
		
		//6.存储盐和加密后的密码
		user.setSalt(salt);
		user.setPassword(md5Password);
		
		user.setCreated(new Date());
		user.setLast_login_time(new Date());

		user.setStatus(0);//未激活

		//生成激活码
		StringBuilder sb=new StringBuilder();
		for(int i=0;i<6;i++){
			sb.append(new Random().nextInt(10));
		}
		String code=sb.toString();
		user.setCode(code);

		userDao.insertUser(user);

		//发送注册邮件
		SendEmail.sendRegisterEmail(user.getUsername(),code,user.getEmail());

	}

	@Override
	public void activation(String username, String code) throws CustomerException {

		User user = userDao.findUserByUsername(username);

		if(user==null){
			throw new CustomerException("没有账户信息!");
		}
		if(user.getStatus()==1){
			throw new CustomerException("账户之前已经激活,不需要重复激活!");
		}
		if(!user.getCode().equals(code)){
			throw new CustomerException("激活码错误!");
		}
		//修改账户状态
		userDao.updateStatus(user.getId(),1);
	}

	@Override
	public User login(String username, String password) throws CustomerException {
		
		//1.判断空
		if(username==null||username.trim().equals("")) {
			throw new CustomerException("用户名不能为空!");
		}
		
		if(password==null||password.trim().equals("")) {
			throw new CustomerException("密码不能为空!");
		}
		
		//2.获取用户的盐
		User user = userDao.findUserByUsername(username);

		if(user==null) {
			throw new CustomerException("用户名或密码错误!");
		}

		if(user.getStatus()==0){
			throw new CustomerException("账号未激活!");
		}


		String salt = user.getSalt();
		
		//3.加密
		String md5Password = Md5Utils.md5Password(password, salt);
		
		//4.对比
		if(!user.getPassword().equals(md5Password)) {
			//密码错误
			throw new CustomerException("用户名或密码错误!");
		}
		
		//更新登录的时间
		user.setLast_login_time(new Date());
		//TODO  修改登录时间
		
		//5.返回用户信息
		return user;
	}
}

2.Servlet

@WebServlet(name = "/activationServlet",value = "/activationServlet")
public class ActivationServlet extends HttpServlet {

    private UserService userService=new UserServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String username=req.getParameter("username");
        String code=req.getParameter("code");

        try {
            userService.activation(username,code);
            resp.getWriter().write("激活成功!");
        } catch (CustomerException e) {
            e.printStackTrace();
            resp.getWriter().write("激活失败!");
        }
    }
}

3.SengMail

public class SendEmail {


    public static void sendRegisterEmail(String username,String code,String email){

        try {
            //创建一个配置文件并保存
            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("1070428xxxx@qq.com", "xxxxxnoubfff");
                }
            });
            //开启debug模式
            session.setDebug(true);
            //获取连接对象
            Transport transport = session.getTransport();
            //连接服务器
            //配置发送人右键的账号和授权码
            transport.connect("smtp.qq.com", "107042xxx@qq.com", "xxxxxndfnoubfff");

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

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

            //邮件接收人
            mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(email));


            String content="<a href='http://localhost:8080/baby/activationServlet?username="+username+"&code="+code+"'>点击激活哦</a>";

            //邮件标题
            mimeMessage.setSubject("注册激活邮件");


            //邮件内容
            mimeMessage.setContent(content, "text/html;charset=gbk");

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

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

        }catch (Exception e){
            e.printStackTrace();
            throw  new RuntimeException("发送注册邮件是失败!");
        }
    }

}
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 深蓝海洋 设计师:CSDN官方博客 返回首页