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('
' + temp_msg + '
同意,不同意', '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'
显示效果:
另外有需要云服务器可以了解下创新互联cdcxhl.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。
分享文章:python发送邮件和附件-创新互联
标题URL:http://scyanting.com/article/csdigs.html