##發送普通txt文件(與發送html郵件不同的是郵件內容設置里的type設置為text,下面代碼為發送普通郵件的另一種方法)
import smtplib
import string
from email.mime.text import MIMEText
from email.utils import formataddr
host = 'smtp.263.net' ##定義smtp主機
SUBJECT = "test smtplib" #定義郵件主題
TO = "xx@xx.com" ##郵件接收人
FROM = "xxxx@xx.com" ##郵件發送人
text = "content" #郵件內容
###拼接郵件主體內容
BODY = "\r\n".join(("From %s:" % FROM,"To: %s" % TO,"Subject:%s" % SUBJECT,"",text)).encode("utf-8")
server = smtplib.SMTP() #創建smtp對象
server.connect(host,"25") ##通過connect方法連接smtp主機
server.starttls() ##啟動安全傳輸模式
server.login("xxx@huixxx.com",'GAxxx@xxx') ##郵箱賬號登錄
server.sendmail(FROM,[TO],BODY)
server.quit() ##斷開smtp連接
發送html郵件
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
HOST = 'smtp.263.net' ##定義smtp主機
SUBJECT = "test smtplib" #定義郵件主題
TO = "xxx@xxx.com" ##郵件接收人(可以為一個列表)
FROM = "xxx@xxx.com" ##郵件發送人
text = "content" #郵件內容
def sendmail():
msg = MIMEText(content,_subtype='html',_charset='utf-8') ##郵件內容,content郵件內容,plain為郵件類型,charset為字符集
msg['From'] = FROM
msg['To'] = TO #如果此處為列表(';'.join(to_list))
msg['Subject'] = SUBJECT
server = smtplib.SMTP("smtp.263.net",25)
server.login("aa@aa.com.cn","xxxxx") #發送者的用戶名和密碼
server.sendmail(FROM,TO,msg.as_string())
server.quit()
sendmail()
發送帶附件的郵件
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import smtplib
#創建一個帶附件的實例
msg = MIMEMultipart()
#構造附件1
file1 = MIMEText(open('d:\\123.rar', 'rb').read(), 'base64', 'utf-8')
file1["Content-Type"] = 'application/octet-stream'
file1["Content-Disposition"] = 'attachment; filename="123.doc"' #這里的filename可以任意寫,寫什么名字,郵件中顯示什么名字
msg.attach(file1)
#加郵件頭
msg['to'] = 'YYY@YYY.com'
msg['from'] = 'XXX@XXX.com'
msg['subject'] = 'hello world' #郵件主題
#發送郵件
server = smtplib.SMTP()
server.connect('smtp.XXX.com',"25")
server.login('XXX','XXXXX') #XXX為用戶名,XXXXX為密碼
server.sendmail(msg['from'], msg['to'],msg.as_string())
server.quit()
發送帶圖片的郵件
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
msg['From'] = "XXX@XXX.com" #郵件發件人
msg['To'] = "YYY@YYY.com" #郵件接收人
msg['Subject'] = "hello world" ##郵件主題
def addimg(img_src,imgid):
fp = open(img_src,'rb')
msgImage = MIMEImage(fp.read())
fp.close()
msgImage.add_header('Conteng-ID',imgid)
return msgImage ##返回msgImage對象
msg_text = MIMEText("""<table><tr><td><img src="cid:aa"></td></tr></table>""","html","utf-8")
#創建MIMEMultipart對象,采用related定義內嵌資源
msg = MIMEMultipart('related')
msg.attach(msg_text)
msg.attach(addimg("C:\aa.img",aa)) ##這里的aa要與msg_text里的aa對應
#發送郵件
server = smtplib.SMTP()
server.connect('smtp.XXX.com',"25")
server.starttls() ##啟動安全傳輸模式
server.login('XXX','XXXXX') #XXX為用戶名,XXXXX為密碼
server.sendmail(msg['From'], msg['To'],msg.as_string()) #這里的前兩個參數自定義
server.quit()