python实现邮件的发送
################简易####################! /usr/bin/env Python
#!coding=utf-8
import smtplib
import random
smtp=smtplib.SMTP("smtp.126.com")#邮件服务器地址
smtp.login("xxx@126.com","xxx")#用户名、密码
smtp.noop()
FROM="xxx@126.com"
TO="xx@gmail.com"
SUBJECT="Hello"
BODY="Hello,Python"
import string
body=string.join((
"From:%s" % FROM,
"To:%s" % TO,
"Subject: %s" % SUBJECT,
"",BODY),
"\r\n")#邮件内容
smtp.sendmail(FROM,,body)#发送
smtp.quit()#退出
#################MIME html+图片附件#####################
#!/usr/bin/env Python
#coding: utf-8
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
sender = 'xxx@126.com'
receiver = 'xxx@qq.com'
subject = 'python email test'
smtpserver = 'smtp.126.com'
username = 'xxx@126.com'
password = 'xxx'
# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = "Link"
# 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>
sdfsaf<br>
safasf<a href="http://www.python.org">link</a> fasfaf.
</p>
</body>
</html>
"""
# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
# 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)
#构造附件
att = MIMEText(open('c:\\0.jpg', 'rb').read(), 'base64', 'utf-8')
att["Content-Type"] = 'application/octet-stream'
att["Content-Disposition"] = 'attachment; filename="1.jpg"'
msg.attach(att)
smtp = smtplib.SMTP()
smtp.connect('smtp.126.com')
smtp.login(username, password)
smtp.sendmail(sender, receiver, msg.as_string())
smtp.quit()
版权声明:本文为博主原创文章,未经博主允许不得转载。
页:
[1]