X0-*_*-0X 20 python email gmail smtplib
我正在尝试学习如何使用 python 发送电子邮件。我读过的所有网络教程都解释了如何使用 Gmail 进行操作。
但是,从 2022 年 5 月 30 日起(尽管每个人都可以自由地使用自己的帐户做任何他想做的事情),Google 制定了一项新政策,规定:
为了确保您的帐户安全,从 2022 年 5 月 30 日开始,Google 将不再支持使用仅要求您提供用户名和密码的第三方应用或设备。登录您的 Google 帐户。
来源: https: //support.google.com/accounts/answer/6010255
所以我的问题是有没有其他方法可以使用 python 发送电子邮件(包括属于其他公司的电子邮件帐户)?
这是我发送电子邮件的功能:
def send_email_fct(filename, filepath, fromaddr, mdpfrom, toaddr):
"""" filename: file name to be sent with extension
filepath: file path of the file to be sent
fromaddr: sender email address
mdpfrom: password of sender email address
toaddr: receiver email address"""
msg = MIMEMultipart() # instance of MIMEMultipart
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "data file"
body_email = "Body_of_the_mail"
msg.attach(MIMEText(body_email, 'plain'))
attachment = open(filepath, 'rb') # open the file to be sent
p = MIMEBase('application', 'octet-stream') # instance of MIMEBase
p.set_payload(attachment.read())
encoders.encode_base64(p)
p.add_header('Content-Disposition', "attachment; filename= %s" % filename)
msg.attach(p) # attach the instance 'p' to instance 'msg'
s = smtplib.SMTP('smtp.gmail.com', 587) # SMTP
s.starttls()
s.login(fromaddr, mdpfrom)
text = msg.as_string()
s.sendmail(from_email_addr, toaddr, text) # sending the email
s.quit() # terminating the session
Run Code Online (Sandbox Code Playgroud)
我收到此错误:
smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials c12-20020aa7d60c000000b0042be14040c1sm2612116edr.86 - gsmtp')
Run Code Online (Sandbox Code Playgroud)
为了解决这个问题,我认为唯一需要更改的行是这一行:
s = smtplib.SMTP('smtp.gmail.com', 587)
Run Code Online (Sandbox Code Playgroud)
如果您知道我可以更改它,或者您看到任何其他错误,这将对我有很大帮助!:-)
X0-*_*-0X 45
这是包含所有主要步骤的更精确答案。我希望它能帮助其他人。
登录您的电子邮件帐户:https ://myaccount.google.com
然后进入安全部分
确保您已开启两步验证并点击“应用程序密码”。截至 2023 年 7 月 9 日,该信息可能不可见,但可通过myaccount.google.com/apppasswords直接访问
希望它能帮助其他人!
| 归档时间: |
|
| 查看次数: |
17114 次 |
| 最近记录: |