写了个发邮件的python代码:
#
-*- coding: utf-8 -*-
#
=================================================
#
#
描述: KEmail 发送邮件类
#
#
作者: hechangmin
#
#
时间: 2008-05-30
#
#
=================================================
import
email
import
mimetypes
from
email.MIMEMultipart
import
MIMEMultipart
from
email.MIMEText
import
MIMEText
from
email.MIMEImage
import
MIMEImage
import
smtplib
from
logger
import
klog
def
sendmail(paramMap):
smtp
=
smtplib.SMTP()
msgRoot
=
MIMEMultipart(
'
related
'
)
msgAlternative
=
MIMEMultipart(
'
alternative
'
)
if
paramMap.has_key(
"
server
"
)
and
paramMap.has_key(
"
user
"
)
and
paramMap.has_key(
"
password
"
):
try
:
smtp.set_debuglevel(
1
)
smtp.connect(paramMap[
"
server
"
])
smtp.login(paramMap[
"
user
"
], paramMap[
"
password
"
])
except
:
klog.error(
"
smtp login exception!
"
)
return
False
else
:
klog.error(
"
Parameters incomplete!
"
)
return
False
#
测试发现 邮件其头部信息 比如标题 发送地址 还有抄送之类 和stmp发送的具体信息脱离。
if
(paramMap.has_key(
"
subject
"
)
and
paramMap.has_key(
"
from
"
)
and
paramMap.has_key(
"
to
"
))
==
False:
klog.error(
"
Parameters incomplete!
"
)
return
False
msgRoot[
'
subject
'
]
=
paramMap[
"
subject
"
]
msgRoot[
'
from
'
]
=
paramMap[
"
from
"
]
if
paramMap.has_key(
"
cc
"
):
msgRoot[
'
cc
'
]
=
paramMap[
"
cc
"
]
msgRoot[
'
to
'
]
=
paramMap[
"
to
"
]
msgRoot.preamble
=
'
This is a multi-part message in MIME format.
'
msgRoot.attach(msgAlternative)
TempAddTo
=
paramMap[
"
to
"
]
if
paramMap.has_key(
"
text
"
):
msgText
=
MIMEText(paramMap[
"
text
"
] ,
'
plain
'
,
'
utf-8
'
)
msgAlternative.attach(msgText)
if
paramMap.has_key(
"
html
"
):
msgText
=
MIMEText(paramMap[
"
html
"
],
'
html
'
,
'
utf-8
'
)
msgAlternative.attach(msgText)
if
paramMap.has_key(
"
image
"
):
fp
=
open(paramMap[
"
image
"
],
'
rb
'
)
msgImage
=
MIMEImage(fp.read())
fp.close()
msgImage.add_header(
'
Content-ID
'
,
'
<image1>
'
)
msgRoot.attach(msgImage)
if
paramMap.has_key(
"
cc
"
):
TempAddTo
=
paramMap[
"
to
"
]
+
"
,
"
+
paramMap[
"
cc
"
]
if
TempAddTo.find(
"
,
"
)
!=
-
1
:
FinallyAdd
=
TempAddTo.split(
"
,
"
)
else
:
FinallyAdd
=
TempAddTo
#
stmp 发送邮件. 发现群发地址用‘,’相隔的字符串,只有一个成功,所以改用列表。
smtp.sendmail(paramMap[
"
from
"
], FinallyAdd, msgRoot.as_string())
smtp.quit()
return
True
#
===Test =========================================
if
__name__
==
'
__main__
'
:
from
mailconf
import
mailmap
sendmail(mailmap)
其中日志记录器,当然你可以不用。
而mailmap的内容:
mailmap = { }
mailmap['server'] = 邮件服务器
mailmap['user'] = 用户名
mailmap['password'] = 密码
mailmap["from"] = 发邮件人地址
#mailmap["cc"] = 抄送地址,以逗号分隔
mailmap["to"] = 接收人地址
mailmap["subject"] = 标题
mailmap["text"] = 信息内容
mailmap["html"] = '<font color = red ><b>信息内容! </b></font>'
其中比较有意思的是,发信信息是可以乱写的。而真正和stmp有密切关系的是 :
smtp.sendmail(paramMap["from"], FinallyAdd, msgRoot.as_string())
也就是上面的什么发信人地址 ,收信人地址 ,抄送人地址都可以是假的。。。
当然愚人节用用还是比较好玩。对高手失效。因为高手觉得奇怪的时候,会去看看邮件的原始属性。。。
哈哈,刚刚我就收到了我梦中情人给我的情书
。。。太yy了。改天通知所有同事到楼下集合。我想应该有不少人会上当。
posted on 2008-06-05 13:25
-274°C 阅读(5706)
评论(3) 编辑 收藏 所属分类:
python