python发送邮件的脚本
python发送邮件的脚本,带有邮件内容与附件,邮件内容为串格式,附件为文件。如果想把某个目录下的所有文件当作附件发送,那请去掉注释。代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#!/usr/bin/python
#coding utf-8
from email.MIMEText import MIMEText
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email import Utils, Encoders
import types
import smtplib
import socket
import base64
import mimetypes
import os
class syk_mail(object):
def __init__(self,smtpserver,sender,password):
self.smtpserver = smtpserver
self.password = password
self.s = None
count = sender.find('@')
if count > -1:
self.postfix = sender
self.sender = sender
else:
self.postfix = ''
self.sender = sender
def sendmailattach(self,receiver,subject,body,path):
try:
msgatt = MIMEMultipart(_charset='gb2312')
msgatt['To'] =receiver
msgatt['From'] = self.sender + self.postfix
msgatt['Subject'] = subject
msgatt['Date'] = Utils.formatdate(localtime=1)
msgatt['Message-ID'] = Utils.make_msgid()
#body = base64.encodestring(body)
msg = MIMEText(body)
msg.add_header('Content-Language','zh-cn')
msg.add_header('Content-Transfer-Encoding','base64')
msg.add_header('content-type','text/html;charset = "gb2312"')
msg.add_header('Content-Disposition','inline')
msgatt.attach(msg)
msgatt.attach(self.attachment(path))
#for root,dirs,files in os.walk(path):
# for filespath in files:
# msgatt.attach(self.attachment(os.path.join(root,filespath)))
if self.s == None:
self.s = smtplib.SMTP(self.smtpserver)
self.s.set_debuglevel(True)
self.s.login(self.sender+self.postfix,self.password)
self.s.sendmail(msgatt['From'],msgatt['To'].split(';'),msgatt.as_string())
except (socket.gaierror,socket.error,socket.herror,smtplib.SMTPException),e:
self.err = str(e)
return False
return True
def attachment(self,filename):
if os.path.exists(filename) == False:
return
fd = open(filename,'rb')
mimetype,mimeencoding = mimetypes.guess_type(filename)
maintype,subtype = "",""
if mimeencoding or (mimetype is None):
mimetype = 'application/octet-stream'
maintype,subtype = mimetype.split('/',1)
retval = MIMEBase(maintype,subtype)
retval.set_payload(fd.read())
Encoders.encode_base64(retval)
retval.add_header('Content-Disposition', 'attchment',filename=filename)
fd.close()
return retval
#end script
页:
[1]