python傳送郵件及附件

2021-09-29 19:59:32 字數 2380 閱讀 7224

import smtplib

import datetime

from email.header import header

from email.mime.text import mimetext

from email.mime.image import mimeimage

from email.mime.multipart import mimemultipart

#建立乙個帶附件的例項

msg = mimemultipart()

#構造附件1

att1 = mimetext(open('d:\\321.txt', 'rb').read(), 'base64', 'gb2312')

att1["content-disposition"] = 'attachment; filename="321.txt"'#這裡的filename可以任意寫,寫什麼名字,郵件中顯示什麼名字

msg.attach(att1)

#構造附件2

att2 = mimetext(open('d:\\123.txt', 'rb').read(), 'base64', 'gb2312')

att2["content-disposition"] = 'attachment; filename="123.txt"'

msg.attach(att2)

smtphost = 'smtp.sina.cn'

sender = '[email protected]'

password = "3434343432432432423"

receiver = ['[email protected]','[email protected]','[email protected]']

#'[email protected]'

date_p = datetime.datetime.now()

str_p = str(date_p)

content = "mimemultipart hello 1870203234e7 " + str(date_p)

#構造正文

att3 = mimetext(content)

msg.attach(att3)

imagefile = 'd:\\_20191121114419.png'

imageapart = mimeimage(open(imagefile, 'rb').read(), imagefile.split('.')[-1])

imageapart.add_header('content-disposition', 'attachment', filename="_20191121114419.png")

msg.attach(imageapart)

pdffile = 'd:\\lte及5g技術比較v1.0(20170420).pdf'

pdfapart.add_header('content-disposition', 'attachment', filename="lte及5g技術比較v1.0(20170420).pdf")

msg.attach(pdfapart)

zipfile = 'd:\\packet20190301.rar'

zipapart.add_header('content-disposition', 'attachment', filename=zipfile)

msg.attach(zipapart)

msg['subject'] = str_p #'email-subject'

msg['from'] = sender

msg['to'] = ",".join(receiver) #receiver[1]

## smtp port 25

smtpserver = smtplib.smtp(smtphost, 25) # smtp

smtpserver.login(sender, password)

smtpserver.sendmail(sender, receiver, msg.as_string())

smtpserver.quit()

print('send success by port 25')

## smtp ssl port 465

# smtpserver = smtplib.smtp_ssl(smtphost, 465) # smtp_ssl

# smtpserver.login(sender, password)

# smtpserver.sendmail(sender, receiver, msg.as_string())

# smtpserver.quit()

# print('send success by port 465')

C 傳送郵件及附件

protected void button1 click object sender,eventargs e c 傳送郵件函式 傳送者郵箱 傳送人 接受者郵箱 收件人 主題 內容 附件 smtp伺服器 郵箱 密碼 public bool sendmail string sfrom,string sf...

python 傳送郵件,附件郵件

1,傳送郵件 import smtplib from email.mime.text import mimetext msg from sunruirui1028 163.com 傳送方郵箱 passwd srui1028 填入傳送方郵箱的授權碼 msg to 1048786140 qq.com 收...

python傳送帶附件郵件

1.不包括附件的郵件 coding utf 8 import smtplib import string 傳送普通的文字郵件 郵件smtp的位址 host smtp.163.com 定義郵件的標題 subject 這是郵件標題 發件人 from 163.com 收件人 to qq.com 傳送的郵件...