java mail 接收邮箱163_JavaMail实现简单邮件开发——163邮箱

  • Post author:
  • Post category:java


1、打开

P0P3/SMTP/IMAP

9822e0d97d517ed824b295895834cb0d.png

c81d636da4776c93429a682c098c21dc.png

2、开发工具类

CodeUtils.java

package com.demo.mymail.utils;

import java.util.UUID;

public class CodeUtils {

public static String generateUniqueCode(){

return UUID.randomUUID().toString().replaceAll(“-“, “”);

}

}

MailUtils.java

package com.demo.mymail.utils;

import java.util.Properties;

import javax.mail.Authenticator;

import javax.mail.Message;

import javax.mail.PasswordAuthentication;

import javax.mail.Session;

import javax.mail.Transport;

import javax.mail.internet.InternetAddress;

import javax.mail.internet.MimeMessage;

import com.sun.mail.util.MailSSLSocketFactory;

public class MailUtils implements Runnable {

private String uName=”XXXXXX@163.com”;

private String authorCode=”my1075125776″;

private String email;

private String msg;

public MailUtils(String email, String msg) {

this.email = email;

this.msg = msg;

}

public void run() {

// 配置

Properties prop=new Properties();

// 设置邮件服务器主机名,这里是163

prop.put(“mail.host”,”smtp.163.com” );

// 发送邮件协议名称

prop.put(“mail.transport.protocol”, “smtp”);

// 是否认证

prop.put(“mail.smtp.auth”, true);

try {

// SSL加密

MailSSLSocketFactory sf = null;

sf = new MailSSLSocketFactory();

// 设置信任所有的主机

sf.setTrustAllHosts(true);

prop.put(“mail.smtp.ssl.enable”, “true”);

prop.put(“mail.smtp.ssl.socketFactory”, sf);

// 创建会话对象

Session session = Session.getDefaultInstance(prop, new Authenticator() {

// 认证信息,需要提供”用户账号”,”授权码”

public PasswordAuthentication getPasswordAuthentication() {

return new PasswordAuthentication(uName, authorCode);

}

});

// 是否打印出debug信息

session.setDebug(true);

// 创建邮件

Message message = new MimeMessage(session);

// 邮件发送者

message.setFrom(new InternetAddress(uName));

// 邮件接受者

message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));

// 邮件主题

message.setSubject(“私人邮件”);

message.setContent(msg, “text/html;charset=UTF-8”);

// Transport.send(message);

// 邮件发送

Transport transport = session.getTransport();

transport.connect();

transport.sendMessage(message, message.getAllRecipients());

transport.close();

} catch (Exception e) {

e.printStackTrace();

}

}

}

3、引入工具包

javax.mail

mail

1.4.7

javax.activation

activation

1.1.1

4、调用服务

package com.demo.mymail.controller;

import com.demo.mymail.utils.MailUtils;

import org.springframework.web.bind.annotation.*;

@RestController

@RequestMapping(“/mymail/mail/”)

public class MailController {

/**

* 发送邮件

* @return

*/

@GetMapping(“send”)

public void send() {

String msg = ”

LIUJIANJIAN


友情链接

“;

new Thread(new MailUtils(“1075125776@qq.com”, msg)).start();

}

}

98d141b93e299c6f8a8b5d6501a3f6de.png

6c7c2f684d1596821aa7236539919169.png



版权声明:本文为weixin_31304817原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。