Python3 发送邮件功能¶
更新日期 2018-11-14
- 2018-11-14 创建文档
发信邮箱是腾讯企业邮箱。开发环境 Windows7。
主要使用smtplib来实现发邮件的功能。
简单的发送邮件功能¶
# 发送邮件
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def send_email():
fromaddr = "from1@your_email.com" # 你的发件邮箱
toaddr = "to1@your_email.com" # 目标邮箱
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "SUBJECT OF THE MAIL"
body = "YOUR MESSAGE HERE"
msg.attach(MIMEText(body, 'plain'))
server = smtplib.SMTP('smtp.exmail.qq.com', 25) # 默认端口25
server.starttls()
server.login(fromaddr, "xxxx密码")
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()
if __name__ == '__main__':
print('start sending email')
send_email()
print('end...')
邮件带上附件¶
Windows下注意文件路径的表达方式。
# 发送邮件
import smtplib
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def send_email(from_email, pwd, target_email_list=[], attachment_file_list=[]):
"""
单独发送邮件
create on 2018-11-14
:param from_email: 源邮箱
:param pwd: 源邮箱密码
:param target_email_list: 目标邮件列表
:param attachment_file_list: 附件路径列表
:return: void
"""
if len(target_email_list) <= 0:
print('ERR: 目标邮件列表为空 -> 退出')
return
for target_email in target_email_list:
print('sending to ' + target_email)
msg = MIMEMultipart()
msg['From'] = from_email
msg['To'] = target_email
msg['Subject'] = "更新"
body = '''尊敬的客户,
你好,请查收文件。
谢谢!
'''
msg.attach(MIMEText(body, 'plain'))
for file_path in attachment_file_list:
filename = str(file_path).split('\\')[-1]
print("file_path " + file_path + " filename: " + filename)
attachment = open(file_path, "rb")
part = MIMEBase('application', 'octet-stream')
part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % filename)
msg.attach(part)
server = smtplib.SMTP('smtp.exmail.qq.com', 25)
server.starttls()
server.login(from_email, pwd)
text = msg.as_string()
server.sendmail(from_email, target_email, text)
server.quit()
if __name__ == '__main__':
print('start sending email')
send_email(from_email="your_email.com",
pwd="密码",
target_email_list=["target1@foxmail.com", "target2@qq.com"],
attachment_file_list=[
r"E:\your_path.rar"])
print('end...')
参考¶
- https://blog.csdn.net/u011846143/article/details/78274911?locationNum=9&fps=1
- http://naelshiab.com/tutorial-send-email-python/
本站说明
一起在知识的海洋里呛水吧。广告内容与本站无关。如果喜欢本站内容,欢迎投喂作者,谢谢支持服务器。如有疑问和建议,欢迎在下方评论~