繁体   English   中英

如何使用python 2.7发送电子邮件附件

[英]how to send email attachement using python 2.7

使用此代码使用 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

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

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

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

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

您需要编辑下面的代码来设置您的 hotmail 的密码(也可能是您的 hotmail 的用户名,如果不是124@hotmail.co.uk ,如您的问题所示)和电子邮件收件人。 出于明显的安全原因,我在测试后从代码中删除了地雷......对我来说:-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 中收到的内容:

Gmail 屏幕截图

您可以使用电子邮件Python 模块做很多事情。 玩得开心!!

编辑:

戈拉米特!! 您关于附加文本文件的评论不会让我放松! :-D我必须自己去看。 按照此问题中的详细说明,我添加了一些代码以将文本文件添加为附件。

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文件,它作为附件正确发送。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM