React中如何通过PDF URL发送邮件?后端PDF链接转附件发送求助
如何将后端返回的PDF链接作为附件发送邮件
核心逻辑是先从目标链接下载PDF内容到内存或临时文件,再将其作为附件添加到邮件中——直接插入链接只会生成超链接,无法实现附件效果。以下是不同技术栈的具体实现方案:
Python 实现示例
使用requests下载PDF,结合smtplib和email库构建并发送邮件:
import smtplib import requests from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.base import MIMEBase from email import encoders from email.utils import formataddr # 邮件基础配置 sender_email = "your_email@example.com" sender_name = "你的名称" receiver_email = "recipient@example.com" smtp_server = "smtp.example.com" smtp_port = 587 smtp_password = "你的SMTP密码" # 后端返回的PDF链接 pdf_url = "https://your-backend-domain.com/path/to/target.pdf" pdf_display_name = "文档附件.pdf" # 1. 下载PDF内容到内存 response = requests.get(pdf_url) response.raise_for_status() # 捕获请求失败的情况 pdf_content = response.content # 2. 构建邮件结构 msg = MIMEMultipart() msg['From'] = formataddr((sender_name, sender_email)) msg['To'] = receiver_email msg['Subject'] = "带有PDF附件的邮件" # 添加邮件正文(可选) body = "您好,附件为您需要的PDF文档,请查收。" msg.attach(MIMEText(body, 'plain', 'utf-8')) # 3. 挂载PDF附件 part = MIMEBase('application', 'octet-stream') part.set_payload(pdf_content) encoders.encode_base64(part) part.add_header('Content-Disposition', f'attachment; filename="{pdf_display_name}"') msg.attach(part) # 4. 发送邮件 with smtplib.SMTP(smtp_server, smtp_port) as server: server.starttls() server.login(sender_email, smtp_password) server.send_message(msg)
Java 实现示例
使用HttpClient下载PDF,结合JavaMail组件完成邮件发送:
import jakarta.mail.*; import jakarta.mail.internet.*; import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.Properties; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; public class PdfAttachmentEmailSender { public static void main(String[] args) throws MessagingException, IOException { // 邮件配置参数 String senderEmail = "your_email@example.com"; String senderPassword = "你的SMTP密码"; String receiverEmail = "recipient@example.com"; String smtpHost = "smtp.example.com"; int smtpPort = 587; // 目标PDF链接 String pdfUrl = "https://your-backend-domain.com/path/to/target.pdf"; String pdfDisplayName = "文档附件.pdf"; // 1. 下载PDF字节内容 CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet(pdfUrl); CloseableHttpResponse response = httpClient.execute(httpGet); byte[] pdfContent = EntityUtils.toByteArray(response.getEntity()); httpClient.close(); // 2. 初始化邮件会话 Properties props = new Properties(); props.put("mail.smtp.host", smtpHost); props.put("mail.smtp.port", smtpPort); 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(senderEmail, senderPassword); } }); // 3. 构建邮件内容 Message message = new MimeMessage(session); message.setFrom(new InternetAddress(senderEmail)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(receiverEmail)); message.setSubject("带有PDF附件的邮件"); // 正文部分 BodyPart bodyPart = new MimeBodyPart(); bodyPart.setText("您好,附件为您需要的PDF文档,请查收。"); // 附件部分 MimeBodyPart attachmentPart = new MimeBodyPart(); attachmentPart.setDataHandler(new DataHandler(new ByteArrayDataSource(pdfContent, "application/pdf"))); attachmentPart.setFileName(pdfDisplayName); // 组合邮件内容 Multipart multipart = new MimeMultipart(); multipart.addBodyPart(bodyPart); multipart.addBodyPart(attachmentPart); message.setContent(multipart); // 4. 发送邮件 Transport.send(message); } }
注:需引入
jakarta.mail和org.apache.httpcomponents依赖
Node.js 实现示例
使用axios下载PDF,结合nodemailer发送邮件:
const nodemailer = require('nodemailer'); const axios = require('axios'); async function sendPdfAttachmentEmail() { // 初始化邮件传输器 const transporter = nodemailer.createTransport({ host: 'smtp.example.com', port: 587, secure: false, auth: { user: 'your_email@example.com', pass: '你的SMTP密码' } }); // 目标PDF链接 const pdfUrl = 'https://your-backend-domain.com/path/to/target.pdf'; const pdfDisplayName = '文档附件.pdf'; // 1. 下载PDF二进制内容 const response = await axios.get(pdfUrl, { responseType: 'arraybuffer' }); const pdfContent = response.data; // 2. 配置邮件参数 const mailOptions = { from: '"你的名称" <your_email@example.com>', to: 'recipient@example.com', subject: '带有PDF附件的邮件', text: '您好,附件为您需要的PDF文档,请查收。', attachments: [ { filename: pdfDisplayName, content: pdfContent, contentType: 'application/pdf' } ] }; // 3. 发送邮件 await transporter.sendMail(mailOptions); console.log('邮件发送成功'); } sendPdfAttachmentEmail().catch(console.error);
注:需提前安装依赖:
npm install nodemailer axios
内容的提问来源于stack exchange,提问作者Hüseyin Erkal
相关产品推荐
相关产品推荐

