我已经有了用 python 发送电子邮件的代码:
\n\ndef send_email_gmail(subject, message, destination):\n """ Send an e-mail using gmail with message to destination email.\n\n Arguments:\n message {str} -- message string to send.\n destination {str} -- destination email (as string)\n """\n server = smtplib.SMTP(\'smtp.gmail.com\', 587)\n server.starttls()\n # not a real email account nor password, its all ok!\n server.login(\'me123@gmail.com\', \'fakepassword111!!!\')\n\n # craft message\n msg = EmailMessage()\n\n message = f\'{message}\\n\'\n msg.set_content(message)\n msg[\'Subject\'] = subject\n msg[\'From\'] = \'me123@gmail.com\'\n msg[\'To\'] = destination\n # send msg\n server.send_message(msg)\nRun Code Online (Sandbox Code Playgroud)\n\n我已经阅读了多个问题(使用 gmail 和 python 发送邮件时登录凭据无法与 Gmail SMTP或SMTPAuthenticationError配合使用)使用),解决了常见错误:
\n\nsmtplib.SMTPAuthenticationError: (534, b\'5.7.14 <https://accounts.google.com/signin/continue?sadfdgjsfgrp=1&dsfgscc=1dsdfgsfg&pldsfgt=AKsdfsdfggsdfggnsbu\\n5.7.14 G0crCr0qSvWTng9xRE_pd3WnK3S2sDMsdfgsdfgX0J-xoetn7aHyFQi2qYrQisdfgsdfgKIwMCcgD7zLB1t7Z\\n5.7.14 -OjHjpJqasdftBuTi9wh0sYlNW637SmPLuMnnLGn_WcZX5TGH4sddsfgXYar-Aasdfw0ctWfLhasdffPQV>\\n5.7.14 Please log in via your web browser and then try again.\\n5.7.14 Learn more at\\n5.7.14 https://support.google.com/mail/answer/787521345364524 n21sm17577sadfdsf46qtn.17 - gsmtp\')\nRun Code Online (Sandbox Code Playgroud)\n\n无论如何,我按照这些答案的建议做了,但我仍然收到错误。所以我决定不再为此使用 gmail。我从一个虚假帐户发送电子邮件只是为了发送电子邮件,因此它的安全性对我来说并不重要。
\n\n那么如何更改上面的代码,以便它适用于不同的电子邮件服务,并且在 python/代码中发送电子邮件更可靠?
\n\n想法答案将包含自包含并包含一个有效的示例脚本。
\n\n当然,我已经检查过在我的假 Gmail 上打开不太安全的应用程序功能,复制粘贴该页面内容的文本:
\n\nTurn off less secure app access\nYour account is vulnerable to malicious activity because you\xe2\x80\x99re allowing apps & devices that use less secure sign-in technology to access your account. You should turn off this type of access. Google will automatically turn this setting OFF if it\xe2\x80\x99s not being used. Learn more\nRun Code Online (Sandbox Code Playgroud)\n\n还有一个黄色感叹号警告我。
\n\n输出EmailMessage():
\nRun Code Online (Sandbox Code Playgroud)\n\n按照建议我粘贴此(空消息)。
\n小智 10
我发现连接到 google SMTP 服务器的最可靠方法是通过应用程序密码。
import smtplib
from email.message import EmailMessage
def send_email_gmail(subject, message, destination):
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
#This is where you would replace your password with the app password
server.login('account@gmail.com', 'App_Password')
msg = EmailMessage()
message = f'{message}\n'
msg.set_content(message)
msg['Subject'] = subject
msg['From'] = 'me123@gmail.com'
msg['To'] = destination
server.send_message(msg)
send_email_gmail('Test subject', 'This is the message', 'to_email@email.com')
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助!
| 归档时间: |
|
| 查看次数: |
10670 次 |
| 最近记录: |