【发布时间】:2020-07-25 08:41:10
【问题描述】:
我有一个基本的 Python 代码,它可以向 Google 表格列表中的地址发送电子邮件。
我想计算 Python 脚本向特定电子邮件地址发送电子邮件的次数。我试着研究它。我没有找到任何与之相关的东西。作为一个完整的初学者并没有帮助我取得太大的进步。
如果有人能指出一个特定的方向,那将是非常有帮助的。提前非常感谢。
下面是代码
import smtplib
import ssl
from email.mime.text import MIMEText # New line
from email.utils import formataddr # New line
# User configuration
sender_email = 'email ID'
sender_name = 'name'
password = "password"
receiver_emails = [RECEIVER_EMAIL_1, RECEIVER_EMAIL_2, RECEIVER_EMAIL_3]
receiver_names = [RECEIVER_NAME_1, RECEIVER_NAME_2, RECEIVER_NAME_3]
# Email text
email_body = '''
This is a test email sent by Python. Isn't that cool?
'''
for receiver_email, receiver_name in zip(receiver_emails, receiver_names):
print("Sending the email...")
# Configurating user's info
msg = MIMEText(email_body, 'plain')
msg['To'] = formataddr((receiver_name, receiver_email))
msg['From'] = formataddr((sender_name, sender_email))
msg['Subject'] = 'Hello, my friend ' + receiver_name
try:
# Creating a SMTP session | use 587 with TLS, 465 SSL and 25
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
# Encrypts the email
context = ssl.create_default_context()
server.starttls(context=context)
# We log in into our Google account
server.login(sender_email, password)
# Sending email from sender, to receiver with the email body
server.sendmail(sender_email, receiver_email, msg.as_string())
print('Email sent!')
except Exception as e:
print(f'Oh no! Something bad happened!n {e}')
finally:
print('Closing the server...')
server.quit()
【问题讨论】:
-
你能分享你的代码吗?
-
已更新代码
-
你想统计每个地址(receiver_email)发送成功的次数吗?
-
是的,没错。脚本成功发送到每个地址的电子邮件
标签: python python-3.x gmail-api google-sheets-api smtplib