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 = '******[email protected]'
password = '******'
#發送人郵箱
sender = '***[email protected]'
#收件人郵箱
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***[email protected]'
#收件人郵箱
receivers = ['568****[email protected]', '*****@163.com']
#郵件主題
subject = 'python_test_email7'
#郵件正文
emailText = '<html><h1>你好!</h1></html>'
#郵件正文格式
emailTextFormat='html'
send_email(user, password, sender, receivers, subject, emailText, emailTextFormat).send()