python发送邮件和附件

2023-01-31 02:01:00 python 发送邮件 附件

发送邮件的时候,需要发送人,收件人,和一台邮件服务器,这里使用python发送一个邮件,主要需要引入smtplib和email库。
下面是源码,粘贴即可用:

#!/usr/bin/env python3
# coding: utf-8
import smtplib
import time
import sys
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

# 发送邮件
def SendMail(mail_list, subject, content):
    from_mail = '这里填入发件人邮箱'
    temp_msg = '武松申请了车费报销'
    msg = MIMEText('</pre><p>' + temp_msg + '</p><a href="/agree">同意</a>,<a href="/disagree">不同意</a><pre>', 'html','utf-8')
    msg['Subject'] = subject
    msg['From'] = from_mail
    msg['To'] = mail_list
    msg['date'] = time.strftime('%a, %d %b %Y %H:%M:%S %z')
    smtp_server = '这里填入邮件服务器的地址'
    s = smtplib.SMTP(smtp_server)
    s.login("填入登录邮件服务器的邮箱", "填入邮箱密码")
    s.sendmail(from_mail, mail_list.split(","), msg.as_string())
    s.quit()

# 发送邮件带附件
def SendMailWithAttachment(mail_list, subject, content, attachment):
    from_mail = '这里填入发件人邮箱'
    msg = MIMEMultipart()
    msg['Subject'] = subject
    msg['From'] = from_mail
    msg['To'] = mail_list
    msg['date'] = time.strftime('%a, %d %b %Y %H:%M:%S %z')
    msg.attach(MIMEText(content, 'html', 'utf-8'))
    att = MIMEText(open(attachment, 'rb').read(), 'base64', 'utf8')
    att["Content-Type"] = 'application/octet-stream'
    att["Content-Disposition"] = 'attachment; filename="%s"' % attachment
    msg.attach(att)
    smtp_server = '这里填入邮件服务器的地址'
    s = smtplib.SMTP(smtp_server)
    s.login("填入登录邮件服务器的邮箱", "填入邮箱密码")
    s.sendmail(from_mail, mail_list.split(","), msg.as_string())
    s.quit()

if __name__ == '__main__':
    if len(sys.argv) < 4:
        print('Usage:', sys.argv[0], ' mail_list subject content [attachment]')
        sys.exit(1)
    content = ""
    if len(sys.argv) == 4:
        SendMail(sys.argv[1], sys.argv[2], content)
    else:
        SendMailWithAttachment(sys.argv[1], sys.argv[2], content, sys.argv[4])

你需要修改的地方是:

from_mail:发件人信息
temp_msg:发送的内容
smtp_server:邮件服务器地址
s.login:邮件服务器登录名和密码

命令行发送:
Python3 sendmail.py '772654204@qq.com' 'python send mail' 'leran is fun'

显示效果:
python发送邮件和附件

相关文章