程序功能:可以指定发件人,指定抄送人,指定标题,指定内容。
邮件发送基于SMTP(简单邮件传输协议),邮件传送代理程序使用SMTP协议来发送电邮到接收者的邮件服务器。SMTP协议只能用来发送邮件,不能用来接收邮件,而大多数的邮件发送服务器都是使用SMTP协议。SMTP协议的默认TCP端口号是25。
并根据该协议,利用了Python的‘smtplib’和‘email‘模块,完成邮件的成功发送。
具体Python代码如下:1.发送普通文本:
import smtplib
from email.mime.text import MIMEText
mailto_list=[ "****@163.com"] #单人多人均可
mail_host="smtp.sina.cn"
mail_user="*****" #邮箱前缀
mail_pass="***" #一般为邮箱密码 但163邮箱是授权码
mail_postfix="sina.cn"
def send_mail(to_list,sub,content):
me="**"+"<"+mail_user+"@"+mail_postfix+">"
msg=MIMEText(content,_subtype='plain',_charset='gb2312')
msg['Subject']=sub
msg['From']=me
msg['To']=";".join(to_list)
try:
server=smtplib.SMTP()
server.connect(mail_host)
server.login(mail_user,mail_pass)
server.sendmail(me,to_list,msg.as_string())
server.close()
return True
except Exception,e:
print str(e);
return False
for i in range(3): #循环
if send_mail(mailto_list,"普通文本","哈哈哈"):
print "done!"
else:
print "failed!"
2.发送含有附件的邮件
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import smtplib
import os
import sys
path = 'd:\\'
file_name = '我的.txt' #可发送附件名是中文的
msg = MIMEMultipart('related')
msg['From'] = '****’#邮箱地址
msg['To'] = '***@bai.com'
msg['Subject'] = os.path.basename(file_name)
# 邮件正文
text = MIMEText('测试!', 'plain', 'gbk')
msg.attach(text)
# 邮件附件
att = MIMEText(open(os.path.join(path, file_name), 'rb').read(), 'base64', 'gbk')
att["Content-Type"] = 'application/octet-stream'
att.add_header('Content-Disposition', 'attachment', filename=('gbk', '', file_name))
msg.attach(att)
smtp = smtplib.SMTP()
smtp.connect('smtp.sina.cn', '25')
smtp.login('******', '***') #第一个是邮箱前缀 第二个是密码
smtp.sendmail(msg['From'], msg['To'], msg.as_string())
smtp.quit()
3.发视带有图片的邮件:
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
import smtplib
import mimetypes
def AutoSendMail():
msg=MIMEMultipart()
msg['to']='***@163.com'
msg['from']='****'
msg['subject'] = '图片'
att=MIMEText("这里是测试图片的发送",'plain','gb2312')
msg.attach(att)
file1="C:\Users\Desktop\Capture.PNG"
image=MIMEImage(open(file1,'rb').read())
image.add_header('Content-ID','<image1>')
msg.attach(image)
server=smtplib.SMTP()
server.connect('smtp.sina.com')
server.login('****’,’***') #邮箱前缀与密码
server.sendmail(msg['from'], msg['to'],msg.as_string())
server.quit()
AutoSendMail()
print '发送成功'