【问题标题】:Cannot send an email with python smtp无法使用 python smtp 发送电子邮件
【发布时间】:2012-11-06 16:55:24
【问题描述】:

我正在使用 python 开发一个应用程序,我需要通过邮件发送文件。我写了一个程序来发送邮件,但不知道有什么问题。代码贴在下面。请任何人帮助我使用这个 smtp 库。有什么我想念的吗?还有谁能告诉我 smtp 中的主机是什么!我正在使用 smtp.gmail.com。 也有人可以告诉我如何通过电子邮件发送文件(.csv 文件)。感谢您的帮助!

#!/usr/bin/python

import smtplib

sender = 'someone@yahoo.com'
receivers = ['someone@yahoo.com']

message = """From: From Person <someone@yahoo.com>
To: To Person <someone@yahoo.com>
Subject: SMTP e-mail test

This is a test e-mail message.
"""

try:
   smtpObj = smtplib.SMTP('smtp.gmail.com')
   smtpObj.sendmail(sender, receivers, message)         
   print "Successfully sent email"
except:
   print "Error: unable to send email"

【问题讨论】:

  • 请提供错误详情。
  • Tichodroma, Lafada, : socket.error:[Errno 10060] 连接尝试失败,因为连接方在一段时间后没有正确响应,或建立连接失败,因为连接的主机没有响应

标签: python smtp


【解决方案1】:

您没有登录。还有几个原因可能导致您无法通过,包括被您的 ISP 阻止、如果无法在您身上获得反向 DNS 时 gmail 将您退回等等。

try:
   smtpObj = smtplib.SMTP('smtp.gmail.com', 587) # or 465
   smtpObj.ehlo()
   smtpObj.starttls()
   smtpObj.login(account, password)
   smtpObj.sendmail(sender, receivers, message)         
   print "Successfully sent email"
except:
   print "Error: unable to send email"

我刚刚注意到您要求能够附加文件。这改变了事情,因为现在你需要处理编码。虽然我不这么认为,但仍然没有那么难遵循。

import os
import email
import email.encoders
import email.mime.text
import smtplib

# message/email details
my_email = 'myemail@gmail.com'
my_passw = 'asecret!'
recipients = ['jack@gmail.com', 'jill@gmail.com']
subject = 'This is an email'
message = 'This is the body of the email.'
file_name = 'C:\\temp\\test.txt'

# build the message
msg = email.MIMEMultipart.MIMEMultipart()
msg['From'] = my_email
msg['To'] = ', '.join(recipients)
msg['Date'] = email.Utils.formatdate(localtime=True)
msg['Subject'] = subject
msg.attach(email.MIMEText.MIMEText(message))

# build the attachment
att = email.MIMEBase.MIMEBase('application', 'octet-stream')
att.set_payload(open(file_name, 'rb').read())
email.Encoders.encode_base64(att)
att.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file_name))
msg.attach(att)

# send the message
srv = smtplib.SMTP('smtp.gmail.com', 587)
srv.ehlo()
srv.starttls()
srv.login(my_email, my_passw)
srv.sendmail(my_email, recipients, msg.as_string())

【讨论】:

  • 感谢您的帮助!我试过这个,但我得到一个错误,用户名和密码不被接受。我对登录(帐户,密码)几乎没有困惑。那个帐户是什么意思。那是发件人邮件帐户还是其他什么。
  • account 是您要从中发送电子邮件的 gmail 帐户 (myemail@gmail.com),password 是该帐户的密码。我刚刚注意到您的附件请求。很快就会更新我的答案。
  • 非常感谢!!请您尽快发布您的更新...(:
  • 哦,所以你知道如果这是一个免费帐户并发送大量电子邮件,gmail 可能会阻止它发送。一个真正的痛苦,没有真正的逻辑,但我已经看过足够多的时间了,除了测试之外不使用 gmail 来做任何事情。通过 gmail 支付帐户虽然没有这个问题,而且非常可靠。
猜你喜欢
  • 2017-02-15
  • 1970-01-01
  • 2017-10-05
  • 1970-01-01
  • 2022-07-20
  • 1970-01-01
  • 2021-07-06
  • 2019-01-23
  • 2020-03-02
相关资源
最近更新 更多