您的位置:首页 > 编程语言 > Python开发

send email w/ python

2012-03-05 00:00 274 查看
simple email w/o attachement:

# Import smtplib for the actual sending function
import smtplib

# Import the email modules we'll need
from email.mime.text import MIMEText

# Open a plain text file for reading.  For this example, assume that
# the text file contains only ASCII characters.
textfile = "d:\\result.html"
fp = open(textfile, 'rb')
# Create a text/plain message
msg = MIMEText(fp.read())
fp.close()

# me == the sender's email address
# you == the recipient's email address
msg['Subject'] = 'The contents of %s' % textfile
me = "rebecca.hu@macrotarget.com"
you = "rebecca.hu@qq.com"
msg['From'] = me
msg['To'] = you

# Send the message via our own SMTP server, but don't include the
# envelope header.
s = smtplib.SMTP('smtp.live.com','587')
s.starttls() #用于加密
s.login("rebecca.hu@macrotarget.com", "mima001")
s.sendmail(me, you, msg.as_string())
s.quit()

email w/ html file:

import smtplib

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

# me == my email address
# you == recipient's email address
me = "rebecca.hu@mail.com"
you = "you@mail.com"

# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative') #实例一个附件
msg['Subject'] = "Link"
msg['From'] = me
msg['To'] = you

# Create the body of the message (a plain-text and an HTML version).
#text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org"
#html = """\
#<html>
#  <head></head>
#  <body>
#    <p>Hi!<br>
#       How are you?<br>
#       Here is the <a href="http://www.python.org">link</a> you wanted.
#   </p>
#  </body>
#
#"""

# Record the MIME types of both parts - text/plain and text/html.
#part1 = MIMEText(text, 'plain')
textfile = "d:\\result.html"
fp = open(textfile, 'rb')
part2 = MIMEText(fp.read(), 'plain')
fp.close()
part2.replace_header("Content-type", "Application/octet-stream;name='result.html'") #重写"Content-type"
part2.add_header("Content-Disposition","attachment;filename='result.html'")#加入"Content-Disposition" 为附件"attachment"
# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
#msg.attach(part1)
msg.attach(part2)
# Send the message via local SMTP server.
s = smtplib.SMTP('smtp.live.com','587')
s.starttls()
s.login("rebecca.hu@mail.com", "12345")
# sendmail function takes 3 arguments: sender's address, recipient's address
# and message to send - here it is sent as one string.
s.sendmail(me, you, msg.as_string())
s.quit()


相关link: http://docs.python.org/library/email-examples.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python email