如何使用python发送邮件附件2.7 [英] how to send email attachement using python 2.7

查看:162
本文介绍了如何使用python发送邮件附件2.7的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用本代码发送电子邮件使用localhost ip时,我收到错误,任何建议如何解决套接字错误?

  def SendTMail(self):
#导入我们需要的电子邮件模块

#打开一个纯文本文件进行阅读。对于这个例子,假设
#文本文件只包含ASCII字符。
#try:
fp = open('testint.txt','rb')
#创建一个文本/纯文本
msg = MIMEText(fp.read())
testfile ='TESTING REPORT'
fp.close()

me ='124@hotmail.co.uk'
你= '123@live.com '
msg ['Subject'] ='%s'的内容%testfile
msg ['From'] = me
msg ['To'] =你

#通过我们自己的SMTP服务器发送消息,但不要包含
#信头。
s = smtplib.SMTP('192.168.1.3')
s.sendmail(me,[you],msg.as_string())
s.quit()

错误如下所示:

 文件x:\example.py,第6行,SendTMail s = smtplib.SMTP('192.168.1.3')
文件x:\Python27\lib\smtplib.py ,行251,在init(代码,msg)= self.connect(主机,端口)
文件x:\Python27\lib\smtplib.py,第311行,在连接self.sock = self._get_socket(host,port,self.timeout)
文件x:\Python27\lib\smtplib.py,第286行,在_get_socket中,返回socket.create_connection((host,port)超时)
文件x:\Python27\lib\socket.py,第571行,在create_connection raise err -
错误:[Errno 10051]尝试对不可达网络进行套接字操作


解决方案

发布之前原始代码,我想根据 Python模块。玩得开心!



编辑:



Gorramit!您关于附加文本文件的评论不会让我放松! : - 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)作为f:
msg.attach(MIMEImage(f.read()))

#开始新的东西

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)

#结束新的东西

smtp_conn = smtplib.SMTP(smtp.live.com,timeout = 10)
printconnection stablished

而且,它的工作原理...我在脚本运行的同一目录中有一个 foo.txt 文件,它作为附件正确发送。


I am getting error when using this code to send email using localhost ip, any suggestion how to solve the socket error?

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()     

the error is shown below:

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

解决方案

Before posting raw code, I'd like to add an small explanation as per the conversation that took place in the comments to your question.

smtplib connects to an existing SMTP server. You can see it more like an Outlook Express. Outlook is a client (or a Mail User Agent, if you wanna get fancy). It doesn't send emails by itself. It connects to whatever SMTP server it has configured among its accounts and tells that server "Hey, I'm user xxx@hotmail.com (and here's my password to prove it). Could you send this for me?"

If you wanted to, having your own SMTP server is doable (for instance, in Linux, an easily configurable SMTP server would be Postfix, and I'm sure there are many for Windows) Once you set one up, it'll start listening for incoming connections in its port 25 (usually) and, if whatever bytes come through that port follow the SMTP protocol, it'll send it to its destination. IMHO, this isn't such a great idea (nowadays). The reason is that now, every (decent) email provider will consider emails coming from unverified SMTP servers as spam. If you want to send emails, is much better relying in a well known SMTP server (such as the one at smtp.live.com, the ones hotmail uses), authenticate against it with your username and password, and send your email relying (as in SMTP Relay) on it.

So this said, here's some code that sends an HTML text with an attachment borrajax.jpeg to an email account relying on smtp.live.com.

You'll need to edit the code below to set your hotmail's password (maybe your hotmail's username as well, if it's not 124@hotmail.co.uk as shown in your question) and email recipients. I removed mines from the code after my tests for obvious security reasons... for me :-D and I put back the ones I saw in your question. Also, this scripts assumes it'll find a .jpeg picture called borrajax.jpeg in the same directory where the Python script is being run:

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()

When I run the example (as I said, I edited the recipient and the sender) it sent an email to a Gmail account using my (old) hotmail account. This is what I received in my Gmail:

There's a lot of stuff you can do with the email Python module. Have fun!!

EDIT:

Gorramit!! Your comment about attaching a text file wouldn't let me relax!! :-D I had to see it myself. Following what was detailed in this question, I added some code to add a text file as an attachment.

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"

And yep, it works... I have a foo.txt file in the same directory where the script is run and it sends it properly as an attachment.

这篇关于如何使用python发送邮件附件2.7的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆