Skip to main content
 首页 » 编程设计

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

2024年11月01日32bjzhanghao

使用此代码使用本地主机 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 

请您参考如下方法:

在发布原始代码之前,我想根据您的 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 文件,它会将其作为附件正确发送。