首页 > 解决方案 > 尝试使用 Gmail 或 Outlook 通过 python 发送电子邮件

问题描述

您好,我对 python 还很陌生,偶然发现了这个很酷的功能,只需几行代码,python 就可以发送电子邮件。

我目前不确定我下面的代码是否有效,或者它是否对我有用?由于我对此完全陌生,因此我无法测试我是否在正确的轨道上。

运行代码时,它编译没有问题,但我从未收到消息。

另外,我正在给自己发送电子邮件,所以我应该很快就能看到它们。

这是我的 Outlook 代码:

import win32com.client as win32
outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.To = 'myemail@hotmail.com'
mail.Subject = 'Hello this is you!
mail.Body = 'Hello!!!!!!'
mail.HTMLBody = '<h2>This is an H2 message</h2>' #this field is optional

# To attach a file to the email (optional):
attachment  = "C:/Users/OneDrive/Documents/Desktop/Social_Network_Ads.csv"
mail.Attachments.Add(attachment)

mail.Send()

这是我的 Gmail 代码:

import smtplib

fromaddr = 'myemail@gmail.com'
toaddrs  = 'myemail@gmail.com'
msg = 'There was a terrible error that occured and I wanted you to know!'


# Credentials (if needed)
username = '###username###'
password = '###password###'

# The actual mail send
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()

请让我知道为什么我没有收到电子邮件或为什么它显示为未发送?

编辑:

我已连接到我的本地 hotmail 帐户并且我已登录到 Gmail,所以我认为这不是连接问题。

当我去检查我的已发送文件夹时,似乎没有发送任何内容

标签: pythonemail

解决方案


推荐阅读