1、发送简单的邮件
import smtplib
from email.mime.text import MIMEText
msg_from='xxxxxxx@sina.cn'
passwd='xxxxxxx'
msg_to='xxxxxxxx@qq.com'
subject="python邮件测试"
content="这是我使用python smtplib及email模块发送的邮件"
msg = MIMEText(content)
msg['Subject'] = subject
msg['From'] = msg_from
msg['To'] = msg_to
try:
smtpObj=smtplib.SMTP('smtp.sina.cn',25)
# smtpObj.connect(mail_host,25)
smtpObj.login(msg_from,passwd)
smtpObj.sendmail(msg_from,msg_to,msg.as_string())
print('邮件发送成功')
except smtplib.SMTPException as e:
print(e)
2、ssl安全登录,打开debug调试
from email.mime.textimport MIMEText
from smtplibimport SMTP_SSL
fromuser='xxxxx@sina.cn'
pwd='xxxxxxxxxxxx'
touser='xxxxxxxxxxxxxxxxxxxx@qq.com'
host_server='smtp.sina.cn'
subject='你好啊小二'
content='测试哟'
#ssl登陆
smtp=SMTP_SSL(host_server)
#set_debuglevel()是用来调试的。参数值为1表示开启调试模式,参数值为0关闭调试模式
smtp.set_debuglevel(1)
smtp.ehlo(host_server)
smp.login(fromuser,pwd)
msg=MIMEText(content,'plain','utf-8')
msg['Subject']=subject
msg['From']=fromuser
msg['To']=touser
smtp.sendmail(fromuser,touser,msg.as_string())
smtp.quit()
print('发送成功')
3、发送附件邮件
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
msg=MIMEMultipart() #创建一个带附件的实例
#构建附件
att=MIMEText(open('D:\\test01.xlsx','rb').read(),'base64','utf-8')
att['Content-Type']='application/octet-stream'
att["Content-Disposition"] = 'attachment; filename="test01.xlsx"'
msg.attach(att)
msg.attach(MIMEText('这是文本+附件的邮件发送测试....','plain','utf-8'))
msg['Subject']=('python邮件测试...')
msg['From']=('xxxxxxxxxxxxx@sina.cn')
msg['To']=('xxxxxxxxxxxxxxx@qq.com')
from_user='xxxxxxxxxxxxx@sina.cn'
pwd=***************************
to_user='xxxxxxxxxxxxxx@qq.com'
smtp_server='smtp.sina.cn'
try:
server=smtplib.SMTP(smtp_server,25)
print('开始登录')
server.login(from_user,pwd)
print('登录成功')
print('邮件开始发送')
server.sendmail(from_user,to_user,msg.as_string())
server.quit()
print('邮件发送成功')
except smtplib.SMTPException as e:
print(e)
4、群发和多附件的邮件
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
def send_mail(receiver,filepath):
sender='xxx@sina.cn'
pwd='xxxxx'
msg=MIMEMultipart()
msg['Subject'] = '你好啊小二'
msg['From'] = sender
smtp_server = 'smtp.sina.cn'
if len(receiver) > 1:
msg['To'] = ','.join(receiver)
else:
msg['To'] = receiver[0]
part = MIMEText('hahaha')
msg.attach(part)
for path in filepath:
name = path.split('\\')[-1]
jpgpart = MIMEApplication(open(path,'rb').read())
jpgpart.add_header('Content-Disposition','attachment',filename=name)
msg.attach(jpgpart)
try:
server = smtplib.SMTP(smtp_server.25)
server.login(sender,pwd)
server.sendmail(sender,receiver,msg.as_string())
server.quit()
print('邮件发送成功')
except Exception as e:
print(str(e))
if __name__ == '__main__':
receiver = ['xxxx','xxxxx','yyyyy']
filepath = ['D:\\xxxx\\a.html','E:\\xxx\\b.jpg']
send_mail(receiver,filepath)
网友评论