python 傳送郵件的示例程式碼(Python2/3都可以直接使用)
阿新 • • 發佈:2020-12-04
傳送普通郵件
傳送文字和html普通郵件如下:
from email.header import Header from email.mime.text import MIMEText from email.utils import parseaddr,formataddr import smtplib def _format_addr(s): name,addr = parseaddr(s) return formataddr((Header(name,'utf-8').encode(),addr)) def get_server(username): """ 通過郵箱地址獲得郵箱伺服器 :param username:使用者名稱,比如:[email protected] :return: 郵箱伺服器地址,可以根據自己實際業務新增,比如:smtp.qq.com """ servers = {'qq' : 'smtp.qq.com','126' : 'smtp.126.com','163' : 'smtp.163.com','139' : 'smtp.139.com'} for key,value in servers.items(): if key in username: return value def send_mail(username,password,to,sender_name,subject,content,email_type): """ :param username: :param password: :param to: 接收者列表 [] :param sender_name: :param subject: :param content: :param email_type: :return: """ from_addr = username password = password to_addr = to smtp_server = get_server(username) # 郵件正文是MIMEText型別 msg = MIMEText('%s'%(content),'%s'%(email_type),'utf-8') msg['From'] = _format_addr('%s<%s>' % (sender_name,from_addr)) msg['To'] = _format_addr('<%s>' % to_addr) msg['Subject'] = Header('%s'%(subject),'utf-8').encode() # 普通登陸埠是25,帶ssl驗證時候埠是465 # smtp_server = 'smtp.exmail.qq.com' # server = smtplib.SMTP_SSL(smtp_server,465) server = smtplib.SMTP(smtp_server,25) server.set_debuglevel(1) server.login(from_addr,password) server.sendmail(from_addr,to_addr,msg.as_string()) server.quit() if __name__ == '__main__': """傳送簡單文字郵件""" username = '******@126.com' password = '******' sender_name = '******@126.com' subject = 'test 郵件' content = '<html><h1>ikeguang 的來信</h1></html> <a href="http://www.ikeguang.com" rel="external nofollow" >ikeguang.com</a></html>' # email_type 取值:plain,文字型別郵件;html,html型別郵件 email_type = 'html' _to = ['******@126.com','******@qq.com'] for to in _to: send_mail(username,email_type) print('send mail to %s success' % to)
傳送帶附件的郵件
def send_mail_multipart(username,email_type): from_addr = username password = password to_addr = to smtp_server = get_server(username) msg = MIMEMultipart() # 郵件正文是MIMEText型別 msg.attach(MIMEText('%s'%(content),'utf-8')) msg['From'] = _format_addr('%s<%s>' % (sender_name,'utf-8').encode() # 讀取附件 filename = 'D:/我的檔案/Codes/PyCode/source/image/0.jpg' with open(filename,'rb') as f: # 設定附件的MIME和檔名,這裡是png型別: mime = MIMEBase('image','jpg',filename='0.jpg') # 加上必要的頭資訊: mime.add_header('Content-Disposition','attachment',filename='0.jpg') mime.add_header('Content-ID','<0>') mime.add_header('X-Attachment-Id','0') # 把附件的內容讀進來: mime.set_payload(f.read()) # 用Base64編碼: encoders.encode_base64(mime) # 新增到MIMEMultipart: msg.attach(mime) # 普通登陸埠是25,帶ssl驗證時候埠是465 # smtplib.SMTP_SSL(smtp_server,[to_addr],msg.as_string()) server.quit()