python学习之三 邮件发送
此代码经过验证可用
单个邮件发送Demo
# -*- coding:utf-8 -*-
import smtplib
from email.mime.text import MIMEText
from email.header import Header
# 邮箱方面需要设置 POP3/SMTP/IMAP 权限
#发送邮箱服务器
smtpserver = 'smtp.163.com'
#发送邮箱用户/密码
user = '******1619@163.com'
password = '******'
#发送人邮箱
sender = '***1619@163.com'
#收件人邮箱
receiver = '******@qq.com'
#邮件主题
subject ='python_test_email'
def sendemail():
try:
# 编写HTML类型的邮件正文
msg = MIMEText('<html><h6>你好!</h6></html>', 'html', 'utf-8')
# 用于邮箱显示标题、发件人、收件人
msg['Subject'] = Header(subject, 'utf-8')
msg['From'] = sender
msg['to'] = receiver
#连接并发送邮件
smtp = smtplib.SMTP()
smtp.connect(smtpserver)
smtp.login(user, password)
smtp.sendmail(sender, receiver, msg.as_string())
smtp.quit()
except Exception as msg:
print msg
sendemail()
多个邮件发送
# -*- coding:utf-8 -*-
import smtplib
from email.mime.text import MIMEText
from email.header import Header
class send_email():
def __init__(self, user, password, sender, s,subject, emailText, emailTextFormat):
self.user = user
self.password = password
self.sender = sender
self.receivers = receivers
self.subject = subject
self.emailText = emailText
self.emailTextFormat = emailTextFormat
def send(self):
try:
# 编写HTML类型的邮件正文
msg = MIMEText(self.emailText, emailTextFormat, 'utf-8')
# 用于邮箱显示标题、发件人、收件人
msg['Subject'] = Header(self.subject, 'utf-8')
msg['From'] = self.sender
receivers = ','.join(self.receivers)
msg['to'] = receivers
# 连接并发送邮件
smtp = smtplib.SMTP()
smtp.connect(smtpserver)
smtp.login(self.user, self.password)
smtp.sendmail(self.sender, self.receivers, msg.as_string())
smtp.quit()
print "发送成功!"
except Exception as msgError:
print msgError
#发送邮箱服务器
smtpserver = 'smtp.126.com'
#发送邮箱用户/密码
user = '******@126.com'
password = '*******'
#发送人邮箱
sender = 'yj***19@163.com'
#收件人邮箱
receivers = ['568****5199@qq.com', '*****@163.com']
#邮件主题
subject = 'python_test_email7'
#邮件正文
emailText = '<html><h1>你好!</h1></html>'
#邮件正文格式
emailTextFormat='html'
send_email(user, password, sender, receivers, subject, emailText, emailTextFormat).send()