java发送邮件(带PDF附件)代码

pom

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>email</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>com.sun.mail</groupId>
            <artifactId>javax.mail</artifactId>
            <version>1.6.2</version>
        </dependency>
        <dependency>
            <groupId>javax.activation</groupId>
            <artifactId
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是Java发送附件邮件的示例代码: ```java import java.util.Properties; import javax.mail.*; import javax.mail.internet.*; public class SendEmailWithAttachment { public static void main(String[] args) { // 收件人邮箱地址 String to = "[email protected]"; // 发件人邮箱地址 String from = "[email protected]"; // 发件人邮箱密码或授权码 String password = "your_password_or_auth_code"; // 邮件主题和正文 String subject = "Test email with attachment"; String body = "Please see the attached file."; // 创建邮件会话 Properties props = new Properties(); props.put("mail.smtp.host", "smtp.example.com"); props.put("mail.smtp.auth", "true"); Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(from, password); } }); try { // 创建邮件消息 MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject(subject); // 创建邮件正文 MimeBodyPart textPart = new MimeBodyPart(); textPart.setText(body); // 创建邮件附件 MimeBodyPart attachmentPart = new MimeBodyPart(); attachmentPart.attachFile("path/to/attachment"); // 将正文和附件添加到邮件消息中 Multipart multipart = new MimeMultipart(); multipart.addBodyPart(textPart); multipart.addBodyPart(attachmentPart); message.setContent(multipart); // 发送邮件 Transport.send(message); System.out.println("Email sent successfully."); } catch (Exception e) { System.err.println("Failed to send email: " + e.getMessage()); } } } ``` 在上面的代码中,需要将以下信息替换为实际的值: - `to`:收件人邮箱地址 - `from`:发件人邮箱地址 - `password`:发件人邮箱密码或授权码 - `subject`:邮件主题 - `body`:邮件正文 - `props.put("mail.smtp.host", "smtp.example.com")`:SMTP服务器地址 另外,需要将附件的文件路径替换为实际的路径。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值