当前位置: 首页 > news >正文

groovy:java 发送一封带有附件的邮件

参阅:菜鸟教程:Java 发送邮件
从 https://gitcode.com/open-source-toolkit/d6296/
下载 javax.mail-1.6.2.jar
本机找到 D:\groovy-2.5.6\lib\extras-jaxb\activation-1.1.1.jar
你可以上网下载 activation-1.1.1.jar
copy javax.mail-1.6.2.jar , activation-1.1.1.jar to D:\groovy-4.0.6\lib\


编写 SendFileEmail.groovy 如下

// 文件名 SendFileEmail.java
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;public class SendFileEmail
{public static void main(String [] args){// 收件人电子邮箱String to = "recipient@163.com";// 发件人电子邮箱String from = "me@163.com";// 指定发送邮件的主机为 localhostString host = "localhost";// 获取系统属性Properties properties = System.getProperties();// 设置邮件服务器properties.setProperty("smtp.163.com", host);// 获取默认的 Session 对象。Session session = Session.getDefaultInstance(properties);try{// 创建默认的 MimeMessage 对象。MimeMessage message = new MimeMessage(session);// Set From: 头部头字段message.setFrom(new InternetAddress(from));// Set To: 头部头字段message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));// Set Subject: 头字段message.setSubject("This is the Subject Line!");// 创建消息部分BodyPart messageBodyPart = new MimeBodyPart();// 消息messageBodyPart.setText("This is message body");// 创建多重消息Multipart multipart = new MimeMultipart();// 设置文本消息部分multipart.addBodyPart(messageBodyPart);// 附件部分messageBodyPart = new MimeBodyPart();String filepath = "D:/test/attach_file.txt"; // 必须是绝对路径String filename = "attach_file.txt";DataSource source = new FileDataSource(filepath);messageBodyPart.setDataHandler(new DataHandler(source));messageBodyPart.setFileName(filename);multipart.addBodyPart(messageBodyPart);// 发送完整消息message.setContent(multipart );//   发送消息Transport.send(message);System.out.println("Sent message successfully....");}catch (MessagingException mex) {mex.printStackTrace();}}
}

运行 groovy SendFileEmail


以下是使用JavaMail发送带附件邮件的完整程序。请确保已添加JavaMail库依赖(如使用Maven,添加以下依赖):

<dependency><groupId>com.sun.mail</groupId><artifactId>javax.mail</artifactId><version>1.6.2</version>
</dependency>

Java程序代码:

// SendEmail_1.goovy
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;public class EmailWithAttachment {public static void main(String[] args) {// 邮件配置信息(请替换为实际值)String host = "smtp.example.com";      // SMTP服务器地址String port = "587";                   // SMTP端口(常用:587或465)String username = "your@email.com";    // 发件邮箱String password = "yourpassword";      // 邮箱密码/授权码String toEmail = "recipient@example.com"; // 收件邮箱// 邮件内容String subject = "测试带附件的邮件";String bodyText = "这是一封包含附件的测试邮件,请查收附件!";// 附件路径(绝对路径)String attachmentPath = "C:/path/to/your/file.pdf"; // 替换为实际文件路径// 设置邮件属性Properties props = new Properties();props.put("mail.smtp.auth", "true");props.put("mail.smtp.starttls.enable", "true"); // 启用TLS加密props.put("mail.smtp.host", host);props.put("mail.smtp.port", port);// 创建Session对象Session session = Session.getInstance(props, new Authenticator() {@Overrideprotected PasswordAuthentication getPasswordAuthentication() {return new PasswordAuthentication(username, password);}});try {// 创建MimeMessage对象Message message = new MimeMessage(session);message.setFrom(new InternetAddress(username));message.setRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));message.setSubject(subject);// 创建邮件正文部分MimeBodyPart textPart = new MimeBodyPart();textPart.setText(bodyText);// 创建邮件附件部分MimeBodyPart attachmentPart = new MimeBodyPart();DataSource source = new FileDataSource(attachmentPath);attachmentPart.setDataHandler(new DataHandler(source));attachmentPart.setFileName(source.getName()); // 设置附件文件名// 组合邮件内容Multipart multipart = new MimeMultipart();multipart.addBodyPart(textPart);multipart.addBodyPart(attachmentPart);// 设置邮件内容message.setContent(multipart);// 发送邮件Transport.send(message);System.out.println("邮件发送成功!");} catch (MessagingException e) {System.err.println("邮件发送失败: " + e.getMessage());e.printStackTrace();}}
}

运行 groovy SendEmail_1

使用说明:

  1. 替换配置信息

    • host:您的SMTP服务器地址(如:smtp.163.com, smtp.qq.com)
    • port:SMTP端口(TLS加密常用587,SSL加密常用465)
    • username:完整的发件邮箱地址
    • password:邮箱密码或授权码(QQ/163等需使用授权码)
    • toEmail:收件人邮箱地址
    • attachmentPath:附件的本地绝对路径(如:D:/reports/monthly.pdf
  2. 常见邮箱SMTP配置

    邮箱服务商SMTP服务器端口加密方式
    163邮箱smtp.163.com465/587SSL/TLS
    QQ邮箱smtp.qq.com465SSL
    Gmailsmtp.gmail.com587TLS
  3. 启用邮箱SMTP服务

    • 163/QQ邮箱:需在网页版邮箱设置中开启SMTP服务并获取授权码
    • Gmail:需在账户设置中启用"不够安全的应用"或使用OAuth2

错误排查:

  1. 认证失败:检查用户名/密码(授权码)是否正确,是否开启SMTP服务
  2. 连接超时:检查网络是否可访问SMTP服务器,尝试关闭防火墙
  3. 附件路径错误:确保文件存在且路径使用正斜杠(/)
  4. 端口问题:尝试切换465/587端口,或调整加密方式(props.put("mail.smtp.ssl.enable", "true")

注意:程序运行时需要网络连接,且附件大小受邮箱服务商限制(通常不超过20MB)。

相关文章:

  • SAP学习笔记 - 开发26 - 前端Fiori开发 OData V2 和 V4 的差异 (Deepseek整理)
  • excel中数字不满六位在左侧前面补0的方法
  • ClusterRole 和 ClusterRoleBinding 的关系及使用
  • 公路水运安全员B证的考试要点、速记口诀及备考指南
  • Shell 编程中的流程控制:从基础到实践
  • 阿里巴巴ROLL:大规模强化学习优化的高效易用解决方案
  • 当SAP系统内计划订单转换为生产订单时发生了什么?
  • Android启动时长优化(kernel部分)
  • 蓝牙音乐(A2DP)音频延迟的一些感想跟分析,让你对A2DP体验更佳深入
  • 什么是预训练?深入解读大模型AI的“高考集训”
  • 获取环境变量的两种方式:getenv()和environ
  • 元器件基础学习笔记——结型场效应晶体管 (JFET)
  • 打卡46天
  • 不要调用 TOARRAY() 从 LARAVEL COLLECTION 中获取所有项目
  • 【Linux】shell中的运行流程控制
  • 平面方程在不同坐标系下的变换与平移
  • Ubuntu 配置使用 zsh + 插件配置 + oh-my-zsh 美化过程
  • TongWeb7.0动态密钥说明
  • 设计一个算法:删除非空单链表L中结点值为x的第一个结点的前驱结点
  • 【LLM】fast-api 流式生成测试
  • 做网站的工具/品牌传播策划方案
  • 恶意点击别人的网站/网站运营优化培训
  • 美国做网站/mac923水蜜桃923色号
  • 旅行网站开发需求说明书/网络营销与直播电商学什么
  • 长安做网站价格/推广一般去哪发帖
  • 淘宝上网站建设为啥这么便宜/5118数据分析平台官网