package com.ruby.controller;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
/**
* @Description 简单邮件发送
* @Author Ruby
* @Date 2020/11/16 13:07
* @Version 1.0
*/
public class JavaMail {
public static void main(String[] args) throws Exception {
Properties properties = new Properties();
//发送服务器需要身份验证
properties.setProperty("mail.smtp.auth", "true");
// 发送邮件协议名称
properties.setProperty("mail.transport.protocol", "smtp");
// smtp服务器地址
properties.put("mail.smtp.host", "smtp.163.com");
//使用JavaMail发送邮件的5个步骤
//1.创建定义整个应用程序所需的环境信息的 Session 对象
Session session = Session.getInstance(properties);
// 设置为debug模式, 可以查看详细的发送 log
session.setDebug(true);
//2.通过session得到transport对象
//发件人邮箱授权码
Transport transport = session.getTransport();
//3、使用邮箱的用户名和授权码连上邮件服务器
transport.connect("******[email protected]","****(代表授权码)");
//4、创建邮件
//邮件内容
Message msg = new MimeMessage(session);
msg.setSubject("邮件标题");
msg.setText("邮件内容");
//发件人邮箱
msg.setFrom(new InternetAddress("******[email protected]"));
//收件人邮箱
msg.setRecipient(Message.RecipientType.TO,
new InternetAddress("******[email protected]"));
msg.saveChanges();
//5、发送邮件
transport.sendMessage(msg, msg.getAllRecipients());
System.out.println("邮件发送成功...");
transport.close();
}
}
配置jar包
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.5.0-b01</version>
</dependency>
/**配置类
*/
package com.ruby.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import java.util.Properties;
@Configuration
public class MailConfig {
private static final String emailProtocol= **;
private static final String emailHost= **;
//邮箱名称
private static final String emailUsername= **;
//邮箱密码
private static final String emailPassword= **;
@Bean
public JavaMailSender javaMailSender() {
JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
javaMailSender.setProtocol(emailProtocol);
javaMailSender.setHost(emailHost);
javaMailSender.setPort(emailPort);
javaMailSender.setUsername(emailUsername);
javaMailSender.setPassword(emailPassword);
javaMailSender.setDefaultEncoding("UTF-8");
Properties javaMailProperties = new Properties();
javaMailProperties.put("mail.auth", true);
javaMailProperties.put("mail." + emailProtocol + ".timeout", 3000);
javaMailSender.setJavaMailProperties(javaMailProperties);
return javaMailSender;
}
package com.ruby.send;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.mail.internet.MimeMessage;
/**
* @Description
* @Author Ruby
* @Date 2020/11/27 16:21
* @Version 1.0
*/
@Controller
@RequestMapping("send")
public class send{
private final Logger log = LoggerFactory.getLogger(this.getClass());
@Autowired
private JavaMailSender javaMailSender;
//发送方邮箱名称
private static final String emailUsername= **;
private static final String UA = "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)";
private String appendixUrl =**;
/**
* 发送邮件
*/
@RequestMapping("/sendMail")
@ResponseBody
public boolean sendMail() {
try {
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
messageHelper.setFrom(emailUsername);
//接收方邮箱名称
messageHelper.setTo("**");
messageHelper.setSubject("你好");
messageHelper.setText("这是一封邮件");
javaMailSender.send(mimeMessage);
log.info("1111111111");
} catch (Exception e) {
log.error("邮件发送异常: ", e);
return false;
}
return true;
}
/**
* 发送带附件的邮件
*/
@RequestMapping("/sendAttachMail")
@ResponseBody
public boolean sendAttachMail() {
try {
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
messageHelper.setFrom(emailUsername);
//接收方的邮件地址
messageHelper.setTo("**");
messageHelper.setSubject("你好");
messageHelper.setText("这是一封邮件");
URLConnection httpURLConnection = null;
try {
httpURLConnection = getInputStreamByUrl(appendixUrl);
InputStream inputStream = httpURLConnection.getInputStream();
//取文件名称
Map<String, List<String>> headerFields = httpURLConnection.getHeaderFields();
//格式:Content-Disposition: attachment; filename=”fname.ext”
if (Objects.nonNull(headerFields) && headerFields.containsKey("Content-Disposition")) {
List<String> strings = headerFields.get("Content-Disposition");
if (!CollectionUtils.isEmpty(strings)) {
String oriFileName = strings.iterator().next();
// String.indexOf("")判断索引下标从几开始
String fileName = oriFileName.substring(oriFileName.indexOf("filename=") + "filename=".length());
messageHelper.addAttachment(URLDecoder.decode(fileName, CommonConstant.CHARSET_UTF8), new ByteArrayResource(transInputStream(inputStream)));
}
}
} finally {
if (Objects.nonNull(httpURLConnection)) {
if (httpURLConnection instanceof HttpURLConnection) {
((HttpURLConnection) httpURLConnection).disconnect();
} else {
((HttpsURLConnection) httpURLConnection).disconnect();
}
}
}
javaMailSender.send(mimeMessage);
log.info("1111111111");
} catch (Exception e) {
log.error("邮件发送异常: ", e);
return false;
}
return true;
}
private URLConnection getInputStreamByUrl(String appendixUrl) throws IOException {
URL url = new URL(appendixUrl);
//创建http链接
URLConnection conn = url.openConnection();
//设置超时间为5秒
conn.setConnectTimeout(5 * 1000);
//防止屏蔽程序抓取而返回403错误
conn.setRequestProperty("User-Agent", UA);
return conn;
}
/**
* 转换流:需要关闭conn的连接,需要手动转换is
*
* @param is
* @return
* @throws IOException
*/
private static byte[] transInputStream(InputStream is) throws IOException {
//data用于存放循环读取的临时数据
byte[] data = new byte[2048];
ByteArrayOutputStream bos = new ByteArrayOutputStream();
BufferedInputStream entryStream = new BufferedInputStream(is, 2048);
int len= 0;
while ((len = entryStream.read(data, 0, 2048)) != -1) {
bos.write(data, 0, len);
}
entryStream.close();
bos.close();
return bos.toByteArray();
}
}