如何使用python发送电子邮件

如何使用python发送电子邮件,python,python-3.x,email,Python,Python 3.x,Email,使用python发送电子邮件的过程是什么。我在研究中发现的要么与我尝试的不同,要么在我尝试实际使用它时不起作用。这似乎不是一项复杂的任务。我在python3.6.3中创建了它,之后我将代码重新编译为python3.2.6,但它可以工作。:) 首先,我们将导入标准Python库中的一些内容 import smtplib from getpass import getpass from email.mime.text import MIMEText 小费! 如果你想通过gmail发送电子邮件,你

使用python发送电子邮件的过程是什么。我在研究中发现的要么与我尝试的不同,要么在我尝试实际使用它时不起作用。这似乎不是一项复杂的任务。

我在python3.6.3中创建了它,之后我将代码重新编译为python3.2.6,但它可以工作。:)

首先,我们将导入标准Python库中的一些内容

import smtplib
from getpass import getpass
from email.mime.text import MIMEText

小费! 如果你想通过gmail发送电子邮件,你必须启用不太安全的功能 应用程序:


我们必须发送电子邮件,以便:

sender = 'example_sender@gmail.com'
receiver = 'example_receiver@gmail.com'

content = """The receiver will see this message.
            Best regards"""

msg = MIMEText(content)
msg['From'] = sender
msg['To'] = receiver
msg['Subject'] = 'Simple app script'

小费!当然,您也可以使用以下方法读取文件中的内容:

with open('/path/to/your/file', 'r') as file:
    content = file.read()

现在我们可以处理“神奇”的服务器端


小费!您可以在电子邮件设置中轻松找到服务器名称。(IMAP/POP) 第页) 这里是我找到的服务器列表:


gmail的解决方案,但您可以使用任何服务器:

smtp_server_name = 'smtp.gmail.com'
#port = '465' # for secure messages
port = '587' # for normal messages

小费!对于这些端口的不同,有以下答案:


我认为这个代码示例非常简单。通过smtplib.SMTP_SSL,我们只能通过安全端口(465)处理服务器。在其他情况下,我们使用不同的方法

if port == '465':
    server = smtplib.SMTP_SSL('{}:{}'.format(smtp_server_name, port))
else :
    server = smtplib.SMTP('{}:{}'.format(smtp_server_name, port))
    server.starttls() # this is for secure reason

server.login(sender, getpass(prompt="Email Password: "))
server.send_message(msg)
server.quit()
当服务器要登录时,您必须在shell中提示后键入密码

就这样。我从命令行在Linux上运行了这个

请随时提问!:)

另外,我在Windows7上新安装的python 3.2.2上测试了它。一切正常。

试试这段代码

import smtplib

# Import the email modules we'll need
from email.mime.text import MIMEText

# Open a plain text file for reading.  For this example, assume that
# the text file contains only ASCII characters.
fp = open(textfile, 'rb')
# Create a text/plain message
msg = MIMEText(fp.read())
fp.close()

# me == the sender's email address
# you == the recipient's email address
msg['Subject'] = 'The contents of %s' % textfile
msg['From'] = me
msg['To'] = you

# Send the message via our own SMTP server, but don't include the
# envelope header.
s = smtplib.SMTP('localhost')
s.sendmail(me, [you], msg.as_string())
s.quit()

你用什么发送它?谷歌的api,微软?我使用的是python?你为此导入了哪些库?在代码顶部,当您编写
import…
时,您导入的是什么?此外-您需要(i)解释您遇到的确切问题和任何错误,以及(ii)附上代码示例,否则此问题将很快被否决或关闭。您需要SMTP服务器,是的。例如,Gmail是常用的,所以它不是一种编码服务。如果你不知道如何编程,我建议谷歌提供免费教程和观看YouTube视频。这看起来会奏效,我会在回家后测试。我得到了以下信息:回溯(最近一次调用):文件“C:/Python32/email.py”,第1行,在导入smtplib文件“C:\Python32\lib\smtplib.py”的第47行,在import email.utils文件“C:/Python32\email.py”的第3行中,在from email.mime.text import MIMEText ImportError中:没有名为mime.textYes的模块可以工作。我在Windows7上试过,新安装的python 3.2.2。我在电子邮件中收到了一条消息。:)尝试重新安装python或只安装新版本。@Iszpiczakowski我在windows 10上