【Java笔记】使用 JavaMail 发送邮件
Java 发送邮件
一、准备工作
1、注册邮箱
注册
2、登录账号,开启 smtp
3、下载依赖包
a、下载
b、若 JDK版本高于8,则可能需要
二、编写代码
public class MailUtil { static Session session = null; // 邮箱前置工作 private static void initSession() { // SMTP服务器 String smtp = "smtp.126.com"; // 账号和密码 String username = "xxxxxxxxxx@xx.com"; // 邮箱 String password = "xxXXxXXXXXX"; // 授权码 // 连接信息 Properties props = new Properties(); props.put("mail.smtp.host", smtp); //SMTP主机号 props.put("mail.smtp.port", "25"); //主机端口号 props.put("mail.smtp.auth", "true"); //是否需要认证 props.put("mail.smtp.starttls.enable", "true"); //启用TLS加密 if (session == null) { // 创建Session session = Session.getInstance(props, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); // 开启调试模式 session.setDebug(true); } } // 发送邮件 public static void sendMail(String email, String title, String content) { // 初始化Session initSession(); // 邮件对象 MimeMessage msg = new MimeMessage(session); try { msg.setFrom(new InternetAddress("xxxxxxxxx@xxx.com")); msg.setRecipient(RecipientType.TO, new InternetAddress(email)); msg.setSubject(title, "utf-8"); // 发送邮件 Multipart multipart = new MimeMultipart(); BodyPart textPart = new MimeBodyPart(); textPart.setContent(content, "text/html;charset=utf-8"); // 附件 BodyPart imagePart = new MimeBodyPart(); imagePart.setFileName("giao.jpg");// 设置附件文件的显示名字 // 数据处理对象(读取附件文件从本地磁盘进行读取) imagePart.setDataHandler( new DataHandler(new ByteArrayDataSource( Files.readAllBytes( Paths.get("C:\Users\Desktop\1.jpg")), "application/octet-stream"))); // 添加至邮件内容 multipart.addBodyPart(textPart);// 添加正文 multipart.addBodyPart(imagePart);// 添加附件 // 设置邮件内容 msg.setContent(multipart); Transport.send(msg); } catch (AddressException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } } }
测试调用
public class Test { public static void main(String[] args) { MailUtil.sendMail("xxxxxxxxxx@xx.com", "Test" , "<b>Hello World</b>"); } }
上一篇:
通过多线程提高代码的执行效率例子
下一篇:
【LeetCode256】粉刷房子