Python(emailメール送受信)

7385 ワード

1.htmlテキストの内容を送信するメール
# smtplib       
import smtplib
# MIMEText         
from email.mime.text import MIMEText
# Header          
from email.header import Header

smtpServer= "smtp.163.com"
sender = "[email protected]"
passWord = "MDZWNINBZEDKXXX"
receiver = "[email protected]"
subject = "Python email test"
#     :        ,    html       ,    utf-8     
msg = MIMEText("

","html","utf-8") # msg["Subject"] = Header(subject,"utf-8") msg["From"] = Header(sender,"utf-8") msg["To"] = Header(receiver) smtp = smtplib.SMTP() smtp.connect(smtpServer) # SMTP smtp.login(sender,passWord) # msg.as_string() MIMEText str smtp.sendmail(sender,receiver,msg.as_string()) smtp.quit()

2、添付のメールを送る
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.mime.multipart import MIMEMultipart

smtpServer= "smtp.163.com"
sender = "[email protected]"
passWord = "MDZWNINBZEDKCXXX"
receiver = "[email protected]"
subject = "Python email test"

#           
msg = MIMEMultipart()
msg["Subject"] = Header(subject,"utf-8")
msg["From"] = Header(sender,"utf-8")
msg["To"] = Header(receiver)

# log.txt      
file = open("log.txt","rb").read()
att = MIMEText(file,"base64","utf-8")
#     filename            
att["Content-Disposition"] = 'attachment; filename="log.txt"'
#            
msg.attach(att)

smtp = smtplib.SMTP()
smtp.connect(smtpServer)
smtp.login(sender,passWord)
smtp.sendmail(sender,receiver,msg.as_string())
smtp.quit()