python使用sendmail在linux下发送邮件

本文介绍如何在Python脚本中通过调用Linux下的sendmail程序实现邮件发送功能。利用os模块的popen函数执行sendmail,并设置发件人、收件人、邮件主题及正文等参数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参考链接:How do I send mail from a Python script?


使用linux下的sendmail程序来发送邮件,利用popen函数(python docs关于popen函数)可以直接调用linux系统程序,需要指定程序所在的位置。

#!/usr/bin/python
# -*- coding: UTF-8 -*- 
#Author: Victor Lv

SENDMAIL = "/usr/sbin/sendmail" #sendmail(可执行程序)所在的路径

sender = "sender@example.com" 
receivers = ["user1@example.com", "user2@example.com"]
subject = "这是邮件标题"
text = "这是邮件正文。"

#将这些元素组合成一条message
message = """\
From: %s
To: %s
Subject: %s

%s
""" % (sender, ", ".join(receivers), subject, text)

# Send the mail
import os

p = os.popen("%s -t -i" % SENDMAIL, "w")
p.write(message)
status = p.close()
if status:
    print "Sendmail exit status", status

python docs中关于发送邮件的其他方法和例子:

email: Examples



Linux上通过Python发送电子邮件通常需要使用内置的`smtplib`库。以下是简单的步骤: 1. **安装必要的库**: 首先,确保已经安装了Python的基础邮件处理库,如`smtplib`和`email`,如果没有安装,可以使用下面命令安装: ``` sudo apt-get install python3-smtplib ``` 2. **导入所需模块**: 在Python脚本中,你需要导入这两个模块: ```python import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText ``` 3. **设置邮箱信息**: 获取SMTP服务器地址、端口、用户名和密码,以及发件人和收件人的邮箱地址: ```python smtp_server = 'smtp.example.com' smtp_port = 587 sender_email = 'sender@example.com' sender_password = 'your_password' recipient_email = 'recipient@example.com' ``` 4. **创建邮件内容**: 使用`MIMEMultipart`创建邮件结构,并添加主题和正文: ```python msg = MIMEMultipart() msg['From'] = sender_email msg['To'] = recipient_email msg['Subject'] = 'Test Email' body = 'This is a test email sent using Python in Linux.' msg.attach(MIMEText(body, 'plain')) ``` 5. **连接并发送邮件**: 连接到SMTP服务器,登录并尝试发送邮件: ```python try: with smtplib.SMTP(smtp_server, smtp_port) as server: server.starttls() # 加密连接 server.login(sender_email, sender_password) text = msg.as_string() server.sendmail(sender_email, [recipient_email], text) print('Email sent successfully.') except Exception as e: print(f"Error occurred: {str(e)}") ``` 6. **运行脚本**: 最后,保存并运行你的Python脚本来发送邮件。 记得替换上述代码中的`smtp.example.com`, `587`, `sender@example.com`, 和 `your_password`为你实际的邮件服务提供商信息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值