1.写在前面:这个知识网上的博客一大堆,我写了估计也没人看,所以我就自己做个笔记用,反正学了忘,忘了学,学了还得忘。话不多说,看代码:
package com.css.utils;import javax.activation.DataHandler;import javax.activation.DataSource;import javax.activation.FileDataSource;import javax.mail.*;import javax.mail.internet.*;import java.io.File;import java.util.Properties;/** * @author 吕海鹏 * @description: * @Date: 2019/1/25 11:26 */public class SendEmail { /** *@name *@description *@time 创建时间:2019/1/25 11:27 *@param to 邮件发送对象 *@param message 邮件发送内容 *@return *@throws Exception *@author xxx *@history 修订历史(历次修订内容、修订人、修订时间等) */ static void sendEmail(String to,String message)throws Exception{ //1、连接邮箱服务器 Properties prop=new Properties(); //设置邮箱发送服务协议为smtp prop.setProperty("mail.transport.protocol", "smtp"); //设置邮箱服务器地址 prop.setProperty("mail.smtp.host", "smtp.qq.com"); // 是否要求身份认证 prop.setProperty("mail.smtp.auth", "true"); // SMTP邮件服务器默认端口 prop.put("mail.smtp.port","25"); // 是否启用调试模式(启用调试模式可打印客户端与服务器交互过程时一问一答的响应消息) prop.setProperty("mail.debug", "true"); Session session= Session.getInstance(prop, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("xxx@qq.com","bsvgvsvillviebhe"); } }); //2.创建邮件内容 MimeMessage message1 =new MimeMessage(session); //2.1设置发件人 message1.setFrom(new InternetAddress("2678983087@qq.com")); //2.2设置收件人 message1.setRecipient(Message.RecipientType.TO,new InternetAddress(to)); //2.3设置邮件主题 message1.setSubject("测试邮件"); //2.4设置邮件内容,纯文本邮件 //message1.setContent(message,"text/html;charset=utf-8"); //message1.setText("nishi shei"); //多内容邮件,part1:文本 MimeMultipart list=new MimeMultipart(); MimeBodyPart part1=new MimeBodyPart(); part1.setContent("shabi","text/html;charset=utf-8"); list.addBodyPart(part1); //part2:附件 MimeBodyPart part2=new MimeBodyPart(); String filename="D:\\文件\\142701199601203312.jpg"; DataSource dataSource =new FileDataSource(filename); part2.setDataHandler(new DataHandler(dataSource)); part2.setFileName(MimeUtility.encodeText(filename)); list.addBodyPart(part2); message1.setContent(list); //3.发送邮件 Transport.send(message1); } public static void main(String[] args) { try { sendEmail("1195664776@qq.com","你是傻逼吗?不,你不是"); } catch (Exception e) { e.printStackTrace(); } }}