好友
阅读权限 10
听众
最后登录 1970-1-1
shyai
发表于 2021-12-16 12:23
本人刚学习python,用python写一些小工具,如有写的不好的地方,请大家多多包含!!
config.ini内容如下:
[sentmail]
#邮箱账号(发件人)
sender=
#邮箱密码
password=
#添加收件人如多个收件人用逗号分割如receivers=a@qq.com,b@qq.com
receivers=xxx@xx.com
SendMail.py内容如下:
import smtplib
from configparser import ConfigParser
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
import os
def SendMail(subject,sendfilepath,text_info):
subject = subject
sendfilepath = sendfilepath
#邮件内容
text_info = text_info
#加载配置文件
config = ConfigParser()
cfg = config.read('config.ini', encoding='utf-8')
sender = config.get('sentmail', 'sender')
password = config.get('sentmail', 'password')
receivers = config.get('sentmail', 'receivers')
#定义邮件的基本格式
msg = MIMEMultipart('mixed')
msg["subject"] = Header(subject, 'utf-8')
msg["From"] = sender
receivers = [i.strip() for i in receivers.split(',')]
msg["To"] = ','.join(receivers)
fname = os.path.basename(sendfilepath)
#添加文本信息
text_info = MIMEText(text_info, 'plain', 'utf-8')
msg.attach(text_info)
#添加附件
file = open(sendfilepath, 'rb').read()
att = MIMEText(file, 'base64', 'utf-8')
att["Content_type"] = 'application/octet-stream'
att.add_header('Content-Disposition', 'attachment', filename = fname)
msg.attach(att)
#发送邮件
try:
smtpObj = smtplib.SMTP(“填写你使用邮箱SMTP”)
smtpObj.login(user=sender, password=password)
smtpObj.sendmail(sender, receivers, msg.as_string())
smtpObj.quit()
print ("邮件发送成功")
except Exception as e:
print ("Error: 无法发送邮件")
免费评分
查看全部评分
发帖前要善用【论坛搜索 】 功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。