Postman的核心功能定位
Postman是一款专注于API开发与测试的工具,本身不具备直接发送电子邮件的能力。若需通过Postman实现邮件发送(含附件),需借助外部工具或服务(如SMTP服务器、命令行工具、Python脚本等)来完成。
若需通过Postman触发邮件发送,可将邮件内容(含附件)通过API请求发送至SMTP服务器。以下是具体步骤:
Settings → General → Email,选择“SMTP”作为发送方式,填写SMTP服务器地址(如Gmail的smtp.gmail.com)、端口(587或465)、用户名(邮箱地址)、密码(应用专用密码或普通密码,需根据SMTP服务商要求)。但此方式需Postman支持SMTP集成(部分版本可能受限)。Tests脚本中编写代码构建邮件对象,例如:pm.test("Send email with attachment", function () {
var emailData = {
"to": "recipient@example.com",
"subject": "Test Email with Attachment",
"text": "This is a test email with an attachment.",
"attachment": [
{
"filename": "example.txt",
"content": "VGhpcyBpcyB0aGUgY29udGVudCBvZiB0aGUgYXR0YWNobWVudC4=" // Base64编码的附件内容
}
]
};
var request = pm.request.url({
method: "POST",
url: "https://your-smtp-api-endpoint/send", // 替换为SMTP服务API地址
header: {
"Content-Type": "application/json",
"Authorization": "Basic " + btoa("your-api-key:") // 若需认证
},
body: {
mode: "raw",
raw: JSON.stringify(emailData)
}
});
request.send();
});
需将recipient@example.com替换为收件人地址,https://your-smtp-api-endpoint/send替换为SMTP服务提供的API地址,your-api-key替换为API密钥(若有)。若无需通过Postman,可直接在Debian系统中使用以下工具发送带附件邮件:
mailx是Debian预装的邮件客户端,支持发送带附件的邮件:
sudo apt-get update && sudo apt-get install mailutils
/etc/mail.rc文件,添加SMTP服务器信息(以Gmail为例):set from="your-email@gmail.com"
set smtp="smtp.gmail.com:587"
set smtp-auth=yes
set smtp-auth-user="your-email@gmail.com"
set smtp-auth-password="your-app-password" # 需开启Gmail“应用专用密码”
mailx的-a参数添加附件,例如:echo "This is the email body." | mailx -s "Email with Attachment" -a /path/to/example.txt recipient@example.com
其中,/path/to/example.txt为附件路径,recipient@example.com为收件人地址。通过Python的smtplib和email模块构建邮件,支持更灵活的附件处理:
send_email.py):import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
def send_email(to, subject, body, attachment_path=None):
sender = "your-email@example.com"
password = "your-password" # 或应用专用密码
msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = to
msg['Subject'] = subject
msg.attach(MIMEText(body, 'plain'))
if attachment_path:
with open(attachment_path, 'rb') as attachment:
part = MIMEBase('application', 'octet-stream')
part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', f'attachment; filename={attachment_path.split("/")[-1]}')
msg.attach(part)
try:
server = smtplib.SMTP('smtp.example.com', 587) # 替换为SMTP服务器地址
server.starttls()
server.login(sender, password)
server.sendmail(sender, to, msg.as_string())
server.quit()
print("Email sent successfully!")
except Exception as e:
print(f"Error: {e}")
# 调用函数发送邮件
send_email(
to="recipient@example.com",
subject="Test Email with Attachment",
body="This is a test email with an attachment.",
attachment_path="/path/to/example.txt" # 可选,不传则无附件
)