我正在尝试使用 Python 发送电子邮件,但不使用典型的付费 API 和第三方服务,仅使用 SMTP。到目前为止我的代码看起来像这样:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def send_email(subject, to_email, message):
password = "passfakeXD"
my_email = "[email protected]"
smtp_obj = smtplib.SMTP('smtp.mail.yahoo.com', 587)
smtp_obj.ehlo()
smtp_obj.starttls()
smtp_obj.ehlo()
smtp_obj.login(my_email, password)
msg = MIMEMultipart()
msg['From'] = my_email
msg['To'] = to_email
msg['Subject'] = subject
msg.attach(MIMEText(message, 'plain'))
smtp_obj.sendmail(msg['From'], [msg['To']], msg.as_string())
smtp_obj.quit()
if __name__ == '__main__':
send_email('Subject: prueba', '[email protected]', 'This was sent via script.')
问题在于,从接下来的几个月开始,Gmail 将不再允许第三方应用程序使用其 SMTP 服务器,因此使用 Gmail 不是一个选择。雅虎也没有,因为他们的“生成应用程序密码”按钮不再起作用。
如何使用 Python 但使用任何其他类型的免费 SMTP 服务器发送电子邮件?我真的不关心安全,因为我只想自动发送一些静态数据电子邮件到我的个人电子邮件。
尝试使用365的smptp
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# Email credentials
smtp_server = 'smtp.office365.com'
smtp_port = 587
email_address = '[email protected]'
email_password = 'your_password' # Use app password if MFA is enabled
# Create the email content
msg = MIMEMultipart()
msg['From'] = email_address
msg['To'] = '[email protected]'
msg['Subject'] = 'Test Email using Office 365 SMTP'
# Email body
body = 'This is a test email sent using Python and Microsoft 365 SMTP server.'
msg.attach(MIMEText(body, 'plain'))
# Establish a connection to the SMTP server
try:
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls() # Secure the connection with TLS
server.login(email_address, email_password) # Login with your email credentials
text = msg.as_string()
# Send the email
server.sendmail(email_address, msg['To'], text)
print("Email sent successfully!")
except Exception as e:
print(f"Failed to send email: {e}")
finally:
server.quit()