一 发送简单的纯文本邮件
import
sys
import
os.path
import
smtplib
import
email
def
sendTextMail(mailhost,sender,recipients,ccto
=
''
,bccto
=
''
,subject
=
''
,message
=
''
, messagefile
=
''
):
try
:
mailport
=
smtplib.SMTP(mailhost)
except
:
sys.stderr.write(
'
Unable to connect to SMTP host "
'
+
mailhost \
+
'
"!\nYou can try again later\n
'
)
return
0
if
(os.path.exists(messagefile)
and
os.path.isfile(messagefile)):
with open(messagefile,
'
r
'
) as f:
message
+=
f.read()
fullmessage
=
'
From:
'
+
'
<
'
+
sender
+
'
> \n
'
+
\
'
To:
'
+
recipients
+
'
\n
'
+
\
'
CC:
'
+
ccto
+
'
\n
'
+
\
'
Bcc:
'
+
bccto
+
'
\n
'
+
\
'
Subject:
'
+
subject
+
'
\n
'
+
\
'
Date:
'
+
email.Utils.formatdate()
+
'
\n
'
+
\
'
\n
'
+
\
message
try
:
#
mailport.set_debuglevel(1)
allrecipients
=
recipients.split(
'
,
'
)
if
not
ccto
==
''
:
allrecipients.extend(ccto.split(
'
,
'
))
if
not
bccto
==
''
:
allrecipients.extend(bccto.split(
'
,
'
))
#
print allrecipients
#
allrecipients must be list type
failed
=
mailport.sendmail(sender, allrecipients, fullmessage)
except
Exception as e:
sys.stderr.write(repr(e))
return
0
finally
:
mailport.quit()
return
1
注意:
recipients,ccto,bccto是接收者的邮件地址,多个地址间使用,分割;
message = '', messagefile = ''表示要发送的email的内容,为可选参数,messagefile表示email的内容来自一个文本文件;
mailport.sendmail(sender, recipients, message)中,message中的from/to/bcc等只是用来email的显示,真正的收件人必须通过recipients来传入,recipients必须为收件人的email地址的数组,
二 发送html的邮件
import
sys
import
os.path
import
smtplib
import
email
from
email
import
encoders
import
mimetypes
from
email.mime.base
import
MIMEBase
from
email.message
import
Message
from
email.mime.audio
import
MIMEAudio
from
email.mime.image
import
MIMEImage
from
email.mime.text
import
MIMEText
from
email.mime.multipart
import
MIMEMultipart
def
getMIMEObj(path):
ctype, encoding
=
mimetypes.guess_type(path)
if
ctype
is
None
or
encoding
is
not
None:
#
No guess could be made, or the file is encoded (compressed), so
#
use a generic bag-of-bits type.
ctype
=
'
application/octet-stream
'
maintype, subtype
=
ctype.split(
'
/
'
,
1
)
msg
=
None
#
print maintype
#
print subtype
if
maintype
==
'
text
'
:
fp
=
open(path)
#
Note: we should handle calculating the charset
msg
=
MIMEText(fp.read(), _subtype
=
subtype, _charset
=
'
utf-8
'
)
fp.close()
elif
maintype
==
'
image
'
:
fp
=
open(path,
'
rb
'
)
msg
=
MIMEImage(fp.read(), _subtype
=
subtype)
fp.close()
elif
maintype
==
'
audio
'
:
fp
=
open(path,
'
rb
'
)
msg
=
MIMEAudio(fp.read(), _subtype
=
subtype)
fp.close()
else
:
fp
=
open(path,
'
rb
'
)
msg
=
MIMEBase(maintype, subtype)
msg.set_payload(fp.read())
fp.close()
#
Encode the payload using Base64
encoders.encode_base64(msg)
#
Set the filename parameter
msg.add_header(
'
Content-Disposition
'
,
'
attachment
'
, filename
=
os.path.basename(path))
return
msg
def
sendHtmlMail(mailhost,subject,sender,recipients,ccto
=
''
,bccto
=
''
,htmldir
=
''
, htmlfile
=
''
):
try
:
mailport
=
smtplib.SMTP(mailhost)
except
:
sys.stderr.write(
'
Unable to connect to SMTP host "
'
+
mailhost \
+
'
"!\nYou can try again later\n
'
)
return
0
msgroot
=
MIMEMultipart(
'
related
'
)
msgroot[
'
From
'
]
=
sender
msgroot[
'
To
'
]
=
recipients
msgroot[
'
Cc
'
]
=
ccto
msgroot[
'
Bcc
'
]
=
bccto
msgroot[
'
Subject
'
]
=
subject
msghtml
=
MIMEMultipart(
'
alternative
'
)
msgroot.attach(msghtml)
if
os.path.exists(os.path.join(htmldir,htmlfile)):
htmlf
=
open(os.path.join(htmldir,htmlfile))
htmlmessage
=
MIMEText(htmlf.read(),
'
html
'
,
'
utf-8
'
)
htmlf.close()
msghtml.attach(htmlmessage)
for
root, subdirs, files
in
os.walk(htmldir):
for
file
in
files:
if
file
==
htmlfile:
continue
else
:
msgroot.attach(getMIMEObj(os.path.join(root,file)))
failed
=
0
try
:
#
mailport.set_debuglevel(1)
allrecipients
=
recipients.split(
'
,
'
)
if
not
ccto
==
''
:
allrecipients.extend(ccto.split(
'
,
'
))
if
not
bccto
==
''
:
allrecipients.extend(bccto.split(
'
,
'
))
#
print allrecipients
failed
=
mailport.sendmail(sender, allrecipients, msgroot.as_string())
print
failed
except
Exception as e:
sys.stderr.write(repr(e))
finally
:
mailport.quit()
return
failed
注意:
htmldir参数表示要发送的html文件所在的目录,此目录下仅包含html文件和html文件引用的相关文件,且所有引用的文件必须与html都在同一目录下,不能有子目录;
htmlfile参数表示要显示到email中的html文件;
例如:
有html文件如下:
d:\html
|--myhtmlemail.html
|--mylinkedtext.txt
|--myimage.gif
且myhtmlemail.html的内容为:
<html>
<body>
<a href="mylinkedtext.txt">message1</a>
<br/>
<h1>This is HTML email sent by python</h1>
<img src="myimage.gif" alt="my message image" />
</body>
</html>
则收到的email如下:
三 使用如下:
mailhost = 'mail-relay.example.com'
sender = "[email protected]"
recipients = "[email protected],[email protected]"
ccto = '[email protected]'
bccto = '[email protected]'
subject = "Testing1"
message = "Testing!\nTesting!\n"
messagefile = "mymessage.txt"
htmldir = 'D:\\html'
htmlfile = 'myhtmleamil.html'
sendTextMail(mailhost,sender,recipients,ccto,bccto,subject,message,messagefile)
sendHtmlMail(mailhost, subject,sender,recipients,htmldir=htmldir,htmlfile=htmlfile)
四 发送带有附件的email
import
sys
import
os.path
import
smtplib
import
email
import
mimetypes
from
email
import
encoders
from
email.mime.base
import
MIMEBase
from
email.message
import
Message
from
email.mime.audio
import
MIMEAudio
from
email.mime.image
import
MIMEImage
from
email.mime.text
import
MIMEText
from
email.mime.multipart
import
MIMEMultipart
def
getMIMEObj(path):
ctype, encoding
=
mimetypes.guess_type(path)
if
ctype
is
None
or
encoding
is
not
None:
#
No guess could be made, or the file is encoded (compressed), so
#
use a generic bag-of-bits type.
ctype
=
'
application/octet-stream
'
maintype, subtype
=
ctype.split(
'
/
'
,
1
)
msg
=
None
#
print maintype
#
print subtype
if
maintype
==
'
text
'
:
fp
=
open(path)
#
Note: we should handle calculating the charset
msg
=
MIMEText(fp.read(), _subtype
=
subtype, _charset
=
'
utf-8
'
)
fp.close()
elif
maintype
==
'
image
'
:
fp
=
open(path,
'
rb
'
)
msg
=
MIMEImage(fp.read(), _subtype
=
subtype)
fp.close()
elif
maintype
==
'
audio
'
:
fp
=
open(path,
'
rb
'
)
msg
=
MIMEAudio(fp.read(), _subtype
=
subtype)
fp.close()
else
:
fp
=
open(path,
'
rb
'
)
msg
=
MIMEBase(maintype, subtype)
msg.set_payload(fp.read())
fp.close()
#
Encode the payload using Base64
encoders.encode_base64(msg)
#
Set the filename parameter
msg.add_header(
'
Content-Disposition
'
,
'
attachment
'
, filename
=
os.path.basename(path))
return
msg
def
sendMail(mailhost,subject,sender,recipients,ccto
=
''
,bccto
=
''
,message
=
''
, payloads
=
''
):
try
:
mailport
=
smtplib.SMTP(mailhost)
except
:
sys.stderr.write(
'
Unable to connect to SMTP host "
'
+
mailhost \
+
'
"!\nYou can try again later\n
'
)
return
0
msgroot
=
MIMEMultipart(
'
mixed
'
)
msgroot[
'
From
'
]
=
sender
msgroot[
'
To
'
]
=
recipients
msgroot[
'
Cc
'
]
=
ccto
msgroot[
'
Bcc
'
]
=
bccto
msgroot[
'
Subject
'
]
=
subject
alternative
=
MIMEMultipart(
'
alternative
'
)
msgroot.attach(alternative)
mes
=
MIMEText(message,
'
plain
'
,
'
utf-8
'
)
alternative.attach(mes)
for
file
in
payloads.split(
'
,
'
):
if
os.path.isfile(file)
and
os.path.exists(file):
msgroot.attach(getMIMEObj(file))
else
:
sys.stderr.write(
"
The file %s cannot be found
"
%
file)
try
:
#
mailport.set_debuglevel(1)
allrecipients
=
recipients.split(
'
,
'
)
if
not
ccto
==
''
:
allrecipients.extend(ccto.split(
'
,
'
))
if
not
bccto
==
''
:
allrecipients.extend(bccto.split(
'
,
'
))
#
print allrecipients
failed
=
mailport.sendmail(sender, allrecipients, msgroot.as_string())
if
failed
==
None:
sys.stderr.write(failed)
return
0
except
Exception as e:
sys.stderr.write(repr(e))
return
0
finally
:
mailport.quit()
return
1
mailhost
=
'
mail-relay.company.com
'
sender
=
"
[email protected]
"
recipients
=
"
[email protected]
"
ccto
=
'
[email protected]
'
bccto
=
'
[email protected]
'
subject
=
"
Testing1
"
message
=
"
Testing!\nTesting!\n
"
sendMail(mailhost,subject,sender,recipients,message
=
message,payloads
=
'
c:\\test\\test.ba,C:\\test\s7\\mytable.txt
'
)
参考:
http://canofy.javaeye.com/blog/265600
http://docs.python.org/library/email-examples.html
http://www.cnblogs.com/itech/archive/2011/02/18/1958114.html
完!