1. 程式人生 > >使用Python傳送多封郵件,百分百可用

使用Python傳送多封郵件,百分百可用

如何使用python通過QQ郵箱傳送郵件,具體實現方式如下:

# -*- coding: UTF-8 -*-
import smtplib
from email.mime.text import MIMEText
from email.header import Header
import socket
'''
SMTP_host:郵件伺服器,
from_account:郵箱賬號/傳送者郵箱
from_passwd:郵箱密碼
to_account:接收者郵箱,是一個list
subject:郵件主題
content:郵件內容
'''
def send_email(SMTP_host, from_account
, from_passwd, to_account, subject, content): # create msg msg = MIMEText(content, 'plain', 'utf-8') msg['Subject'] = Header(subject, 'utf-8') # subject msg['From'] = from_account msg['To'] = ';'.join(to_account) try: #需要使用支援SSL協議的方法,使用smtplib.SMTP郵件只能163之間傳送,無法和QQ等其他郵箱互發 email_client = smtplib.SMTP_SSL
(SMTP_host, '465') email_client.login(from_account, from_passwd) email_client.sendmail(from_account, to_account, msg.as_string()) except smtplib.SMTPException as e: print(e) print('郵件傳送失敗!') except socket.gaierror as e: print(e) print('郵件伺服器連結失敗!') else: email_client.quit
() print('成功傳送%s封郵件.' % len(to_account)) if __name__ == "__main__": from_account = '4********[email protected]' #每個郵箱伺服器對應的授權不一樣的,得到的密碼也不一樣。這裡的是授權密碼,不是登入密碼。 from_passwd = '**************' to_account = ['4*********[email protected]','l*********[email protected]'] #郵件傳送的伺服器 SMTP_host = 'smtp.qq.com' subject = '傳送郵件' content = ''' 請注意,請注意: 傳送郵件~~~~~~ 傳送~~~ 傳送成功了~~~~~~~ ''' send_email(SMTP_host, from_account, from_passwd, to_account, subject, content)