python3利用smtplib发送、抄送邮件并附带附件
1. 导包
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import logging
2. 定义发送邮件函数
def send_mail(MAIL_SERVER, MAIL_USERNAME, MAIL_PASSWORD, accept_list, Cc_list, SUBJECT, text, file_name):
message = MIMEMultipart()
message['From'] = MAIL_USERNAME # 发件人
message['To'] = ";".join(accept_list) # 收件人,将列表转换为字符串
message["Cc"] = ";".join(Cc_list) # 抄送人,将列表转换为字符串
message['Subject'] = SUBJECT # 邮件主题
message.attach(MIMEText(text, 'plain', 'utf-8')) # 格式化邮件内容,编码为utf-8
att1 = MIMEText(open(file_name, 'rb').read(), 'base64', 'utf-8') # 添加附件
att1["Content-Type"] = 'application/octet-stream' # 设置类型
att1["Content-Disposition"] = 'attachment; filename="{0}"'.format("test.xlsx") # 设置邮件用现实的名称
message.attach(att1)
try:
mailServer = smtplib.SMTP(MAIL_SERVER, 25) # 25为端口号(邮件)
# 登录邮箱
mailServer.login(MAIL_USERNAME, MAIL_PASSWORD) # 需要的是,邮箱的地址和授权密码
# 发送文件
mailServer.sendmail(MAIL_USERNAME, accept_list + Cc_list, message.as_string())
mailServer.close() # 关闭连接
return True
except Exception as e:
# logging.debug(e)
print(e)
return False
3. 调用发送邮件函数
def main():
MAIL_SERVER = 'smtp.qq.com' # smtp服务器
MAIL_USERNAME = '*****@qq.com' # 发件人
MAIL_PASSWORD = '**********' # 发送者授权码
accept_list = ['****@163.com', '*****@qq.com'] # 收件人
Cc_list = ['*****@qq.com', '*****@qq.com'] # 抄送人
SUBJECT = "send mail test" # 主题
text = "test page" # 内容
file_name = "a.xlsx" # 上传附件名称(当前路径)
if send_mail(MAIL_SERVER, MAIL_USERNAME, MAIL_PASSWORD, accept_list, Cc_list, SUBJECT, text, file_name):
logging.debug("Send mail succed!")
else:
logging.debug("Send mail failed")
if __name__ == '__main__':
main()