如何使用Camunda的camunda-bpm-mail扩展发送带附件的邮件?
使用camunda-bpm-mail添加邮件附件的实现方法
方法1:BPMN流程中直接配置附件参数
camunda-bpm-mail的send任务支持通过attachments参数指定附件,步骤如下:
- 打开BPMN编辑器,选中邮件发送任务,进入Properties面板的Extension Properties
- 添加键为
attachments的属性,值为附件路径,多个附件用逗号分隔,示例:/tmp/report.pdf,classpath:templates/attachment.docx
路径支持两种格式:
- 本地绝对路径:服务器上文件的完整路径
- 类路径资源:以
classpath:开头,指向项目resources目录下的文件
方法2:自定义JavaDelegate实现灵活附件处理
如果需要动态生成附件、从数据库读取附件等场景,可自定义JavaDelegate:
import org.camunda.bpm.engine.delegate.DelegateExecution; import org.camunda.bpm.engine.delegate.JavaDelegate; import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import java.util.Properties; public class SendMailWithAttachmentDelegate implements JavaDelegate { @Override public void execute(DelegateExecution execution) throws Exception { // SMTP配置 Properties props = new Properties(); props.put("mail.smtp.host", "你的SMTP服务器地址"); props.put("mail.smtp.port", "587"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); Session session = Session.getInstance(props, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("你的邮箱账号", "你的邮箱密码/授权码"); } }); // 构建邮件 Message message = new MimeMessage(session); message.setFrom(new InternetAddress("sender@example.com")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("recipient@example.com")); message.setSubject("带附件的测试邮件"); // 邮件正文 MimeBodyPart bodyPart = new MimeBodyPart(); bodyPart.setText("这是一封包含附件的测试邮件"); // 附件部分 MimeBodyPart attachmentPart = new MimeBodyPart(); attachmentPart.attachFile("/tmp/report.pdf"); // 替换为实际附件路径 // 组合内容 Multipart multipart = new MimeMultipart(); multipart.addBodyPart(bodyPart); multipart.addBodyPart(attachmentPart); message.setContent(multipart); // 发送邮件 Transport.send(message); } }
将上述类部署到Camunda后,在BPMN任务中配置该Delegate作为执行逻辑即可。
补充
若使用Spring Boot集成camunda-bpm-mail,可借助Spring的JavaMailSender简化邮件配置,无需手动构建Session和邮件对象,进一步降低代码复杂度。
内容的提问来源于stack exchange,提问作者John Smith
相关产品推荐
相关产品推荐

