python发送单人邮件(附件,图片,html),多人邮件

单人邮件

# -- coding: utf-8 --
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header

smtpserver = 'smtp.163.com'  # 163邮箱服务器地址
smtpport = 465  # 163邮箱ssl协议端口号
sender = '[email protected]'  # 发送者邮箱
# sender_pwd = input('请输入密码')#并开启客户端授权密码时会设置授权码并非登录密码
sender_pwd = "xxxxx"  # 授权码自行去网页开启设置
rece = '[email protected]'  # 收件人邮箱
mail_username = ''

# 创建一个带附件的邮件实例
message = MIMEMultipart()
# 编辑邮件的内容

# 往邮件容器中添加内容。这是邮件的主体
mail_title = 'python自动发邮件'
# mail_inside = MIMEText(r'这是我程序自动发送的。内含图片', 'plain', 'utf-8')#主体文件
zhengwen = """
      各位好:

"""
mail_inside = MIMEText(zhengwen, 'plain', 'utf-8')
# 邮件的其他属性
message['From'] = sender
message['To'] = rece
message['Subject'] = Header(mail_title, 'utf-8')
message.attach(mail_inside)

#构造附件txt附件1
attr1 = MIMEText(open(r'D:\houseinformation.txt', 'rb').read(), 'base64', 'utf-8')
attr1["content_Type"] = 'application/octet-stream'
attr1["Content-Disposition"] = 'attachment; filename="houseinformation.txt"'  # 表示这是附件,名字是啥
message.attach(attr1)

#  构造图片附件2
att2 = MIMEText(open(r'D:\flower.jpg', 'rb').read(), 'base64', 'utf-8')
att2["Content-Type"] = 'application/octet-stream'
att2["Content-Disposition"] = 'attachment; filename="flower.jpg"'
message.attach(att2)
# 构造html附件
att3 = MIMEText(open('report_test.html', 'rb').read(), 'base64', 'utf-8')
att3["Content-Type"] = 'application/octet-stream'
att3["Content-Disposition"] = 'attachment; filename="report_test.html"'
message.attach(att3)
try:
    smtpobj = smtplib.SMTP_SSL(smtpserver, port=smtpport)
    smtpobj.login(sender, sender_pwd)
    smtpobj.sendmail(sender, rece, message.as_string())
    print('邮件发送成功')
    smtpobj.quit()
except:
    print("邮件发送失败")

多人邮件

import smtplib
from email.header import Header  # 用来设置邮件头和邮件主题
from email.mime.text import MIMEText  # 发送正文只包含简单文本的邮件,引入MIMEText即可

# 发件人和收件人
sender = '[email protected]'

# 所使用的用来发送邮件的SMTP服务器
smtpServer = 'smtp.163.com'

# 发送邮箱的用户名和授权码(不是登录邮箱的密码)
username = '[email protected]'
password = 'xxxx'

mail_title = 'xxxxxx'  # 邮件主题
mail_body = 'xxxxxxxx'  # 邮件内容

msg_to = ['xxxxx,xxxxx']#收件人

# 创建一个实例
message = MIMEText(mail_body, 'plain', 'utf-8')  # 邮件正文
message['From'] = sender  # 邮件上显示的发件人
message['To'] = ','.join(msg_to)  # 邮件上显示的收件人
message['Subject'] = Header(mail_title, 'utf-8')  # 邮件主题

try:
    smtp = smtplib.SMTP()  # 创建一个连接
    smtp.connect(smtpServer)  # 连接发送邮件的服务器
    smtp.login(username, password)  # 登录服务器
    smtp.sendmail(sender, message['To'].split(','), message.as_string())  # 填入邮件的相关信息并发送
    print("邮件发送成功!!!")
    smtp.quit()
except smtplib.SMTPException:
    print("邮件发送失败")

猜你喜欢

转载自blog.csdn.net/qq_34237321/article/details/102783589