【问题标题】:how to send email attachement using python 2.7如何使用 python 2.7 发送电子邮件附件
【发布时间】:2014-05-27 14:08:42
【问题描述】:

使用此代码使用 localhost ip 发送电子邮件时出现错误,有什么建议可以解决套接字错误吗?

def SendTMail(self):
# Import the email modules we'll need

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

    me = '124@hotmail.co.uk'
    you = '123@live.com'
    msg['Subject'] = 'The contents of %s' % testfile
    msg['From'] = me
    msg['To'] = you

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

错误如下图:

File "x:\example.py", line 6, in SendTMail s = smtplib.SMTP('192.168.1.3') 
File "x:\Python27\lib\smtplib.py", line 251, in init (code, msg) = self.connect(host, port)
File "x:\Python27\lib\smtplib.py", line 311, in connect self.sock = self._get_socket(host, port, self.timeout)
File "x:\Python27\lib\smtplib.py", line 286, in _get_socket return socket.create_connection((host, port), timeout)
File "x:\Python27\lib\socket.py", line 571, in create_connection raise err – 
error: [Errno 10051] A socket operation was attempted to an unreachable network

【问题讨论】:

  • 能否请您也发布错误?
  • 您的计算机中有 SMTP 服务器吗?
  • 错误:[Errno 10051] 尝试对无法访问的网络进行套接字操作,此错误
  • 好吧,我没有 SMTP 服务器,我正在尝试从我的本地网络(家庭)发送它
  • 但 smtplib.SMTP 连接到 现有 SMTP 服务器以发送电子邮件。您需要先安装(和配置)一个

标签: python email


【解决方案1】:

在发布原始代码之前,我想根据 cmets 中发生的对话向您的 question 添加一个小解释。

smtplib 连接到现有的 SMTP 服务器。您可以看到它更像是 Outlook Express。 Outlook 是一个客户端(或Mail User Agent,如果你想看中的话)。它不会自己发送电子邮件。它连接到它在其帐户中配置的任何 SMTP 服务器,并告诉该服务器 “嘿,我是用户 xxx@hotmail.com(这是我的密码来证明这一点)。你能为我发送这个吗?”

如果您愿意,拥有自己的 SMTP 服务器是可行的(例如,在 Linux 中,一个易于配置的 SMTP 服务器将是 Postfix,我相信有很多适用于 Windows)将开始侦听其端口 25(通常)中的传入连接,并且如果通过该端口的任何字节跟随 SMTP protocol,它会将其发送到其目的地。恕我直言,这不是一个好主意(现在)。原因是现在,每个(体面的)电子邮件提供商都会将来自未经验证的 SMTP 服务器的电子邮件视为垃圾邮件。如果您想发送电子邮件,最好依靠一个知名的 SMTP 服务器(例如smtp.live.com 的那个,hotmail 使用的服务器),使用您的用户名和密码对其进行身份验证,然后发送您的电子邮件依赖(如SMTP Relay) 就可以了。

也就是说,这里有一些代码将带有附件 borrajax.jpeg 的 HTML 文本发送到依赖于 smtp.live.com 的电子邮件帐户。

您需要编辑下面的代码来设置您的 hotmail 密码(如果不是 124@hotmail.co.uk,如您的问题所示)和电子邮件收件人,也可能是您的 hotmail 用户名。出于明显的安全原因,我在测试后从代码中删除了地雷......对我来说 :-D 我放回了我在你的问题中看到的那些。此外,此脚本假定它会在运行 Python 脚本的同一目录中找到名为 borrajax.jpeg.jpeg 图片:

import smtplib
from email.mime.image import MIMEImage
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

def send_mail():
    test_str="This is a test"
    me="124@hotmail.co.uk"
    me_password="XXX"   # Put YOUR hotmail password here
    you="123@live.com"
    msg = MIMEMultipart()
    msg['Subject'] = test_str
    msg['From'] = me
    msg['To'] = you
    msg.preamble = test_str
    msg_txt = ("<html>"
                "<head></head>"
                "<body>"
                    "<h1>Yey!!</h1>"
                    "<p>%s</p>"
                "</body>"
            "</html>" % test_str)
    msg.attach(MIMEText(msg_txt, 'html'))
    with open("borrajax.jpeg") as f:
        msg.attach(MIMEImage(f.read()))
    smtp_conn = smtplib.SMTP("smtp.live.com", timeout=10)
    print "connection stablished"
    smtp_conn.starttls()
    smtp_conn.ehlo_or_helo_if_needed()
    smtp_conn.login(me, me_password)
    smtp_conn.sendmail(me, you, msg.as_string())
    smtp_conn.quit()

if __name__ == "__main__":
    send_mail()

当我运行示例时(正如我所说,我编辑了收件人和发件人),它使用我的(旧)hotmail 帐户向 Gmail 帐户发送了一封电子邮件。这是我在 Gmail 中收到的内容:

您可以使用email Python 模块做很多事情。玩得开心!

编辑:

戈拉米特!!您关于附加文本文件的评论不会让我放松! :-D 我必须亲眼看到。按照in this question 的详细说明,我添加了一些代码以将文本文件添加为附件。

msg_txt = ("<html>"
            "<head></head>"
            "<body>"
                "<h1>Yey!!</h1>"
                "<p>%s</p>"
            "</body>"
        "</html>" % test_str)
msg.attach(MIMEText(msg_txt, 'html'))
with open("borrajax.jpeg", "r") as f:
    msg.attach(MIMEImage(f.read()))
#
# Start new stuff
#
with open("foo.txt", "r") as f:
    txt_attachment = MIMEText(f.read())
    txt_attachment.add_header('Content-Disposition',
                              'attachment',
                               filename=f.name)
    msg.attach(txt_attachment)
#
# End new stuff
#
smtp_conn = smtplib.SMTP("smtp.live.com", timeout=10)
print "connection stablished"

是的,它可以工作...我在运行脚本的同一目录中有一个foo.txt 文件,它以附件的形式正确发送。

【讨论】:

  • 非常感谢....iT WORKS。我现在正试图弄清楚如何发送文本文件附件。谢谢你的帮助;)
  • @user3395021,对于文本附件,请查看:stackoverflow.com/questions/9541837/… :-)(我还没有测试过,但应该可以)哦,很高兴我帮忙了。
  • 刚刚添加了如何在验证其工作后附加 .txt。现在不要问如何附加PDF!...我想看电影!哈哈...(开玩笑)玩得开心编码! :-)
  • 大声笑老兄,它在以纯文本形式发送时有效,但作为附件,我想我需要某种编码器嘿嘿..我到了..:P
  • 这很奇怪......你看到我对我的回答的编辑了吗(到最后)?我在我的 Gmail 中获取文件作为附件。
猜你喜欢
  • 2023-02-22
  • 2015-02-21
  • 2017-11-20
  • 2015-06-19
  • 1970-01-01
  • 2021-03-06
相关资源
最近更新 更多