linux下python如何使用sendmail发送邮件
发布时间:2023-05-18 06:30:27
在Linux系统中,可以使用Python的smtplib和email模块来发送邮件。具体步骤如下:
1. 安装smtplib和email模块
如果没有安装smtplib和email模块,可以使用以下命令来安装:
sudo apt-get install python-smtplib sudo apt-get install python-email
2. 导入所需模块
在Python脚本中,需要导入smtplib和email模块:
import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart
其中,MIMEText模块用于创建邮件正文,MIMEMultipart模块用于创建带附件的邮件。
3. 创建邮件
使用MIMEText创建邮件正文:
msg = MIMEText('邮件正文')
msg['Subject'] = '邮件主题'
msg['From'] = '发件人邮箱'
msg['To'] = '收件人邮箱'
如果需要发送带附件的邮件,可以使用MIMEMultipart创建邮件:
msg = MIMEMultipart()
msg['Subject'] = '邮件主题'
msg['From'] = '发件人邮箱'
msg['To'] = '收件人邮箱'
# 添加正文
body = MIMEText('邮件正文')
msg.attach(body)
# 添加附件
att = MIMEText(open('filename', 'rb').read(), 'base64', 'utf-8')
att['Content-Type'] = 'application/octet-stream'
att['Content-Disposition'] = 'attachment; filename="filename"'
msg.attach(att)
创建邮件正文时,需要指定邮件主题,发件人、收件人和邮件正文内容。对于带附件的邮件,除了添加正文外,还需要添加附件。添加附件时,需要指定Content-Type和Content-Disposition,Content-Type用于指定附件的MIME类型,Content-Disposition用于指定附件的展示方式。
4. 发送邮件
使用smtplib发送邮件:
smtp = smtplib.SMTP()
smtp.connect('smtp服务器地址')
smtp.login('发件人邮箱', '邮箱密码')
smtp.sendmail(msg['From'], msg['To'], msg.as_string())
smtp.quit()
在发送邮件之前,需要连接到SMTP服务器并进行验证。连接时,需要指定SMTP服务器地址和端口号。验证时,需要输入发件人的邮箱和邮箱密码。发送邮件时,需要指定发件人、收件人和邮件内容。最后,断开连接。
完整代码:
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
msg = MIMEMultipart()
msg['Subject'] = '邮件主题'
msg['From'] = '发件人邮箱'
msg['To'] = '收件人邮箱'
# 添加正文
body = MIMEText('邮件正文')
msg.attach(body)
# 添加附件
att = MIMEText(open('filename', 'rb').read(), 'base64', 'utf-8')
att['Content-Type'] = 'application/octet-stream'
att['Content-Disposition'] = 'attachment; filename="filename"'
msg.attach(att)
smtp = smtplib.SMTP()
smtp.connect('smtp服务器地址')
smtp.login('发件人邮箱', '邮箱密码')
smtp.sendmail(msg['From'], msg['To'], msg.as_string())
smtp.quit()
需要注意的是,有些电子邮件服务商可能会禁用SMTP功能或需要使用SSL连接。在这种情况下,需要根据不同服务商的要求来修改代码。
