求助用python發帶附件qq郵件,發不出去,是怎么回事?
代碼編譯成功,stmp服務也開啟了,用的授權碼登錄,郵件就是發不出去!請教論壇里的朋友幫忙,感激涕零。
以下是完整代碼:
from smtplib import SMTP_SSL
from email.mime.text import MIMEText #構建文字版的正文
from email.mime.multipart import MIMEMultipart #構造郵件主題
from email.mime.application import MIMEApplication #用來添加附件
from email.header import Header
host_server = 'smtp.qq.com'
sender = '[email protected]'
pwd = 'xxxxxxxx'
receiver = '[email protected]'
mail_title = 'python測驗郵件 ' #郵件標題
mail_content ="人生苦短,我用Python!" #郵件正文
msg = MIMEMultipart() #初始化郵件主體
msg["Subject"] = Header(mail_title,'utf-8') #構建標題
msg["From"] = sender #設定寄件人
msg["To"] = Header(receiver, 'utf-8') #設定收件人
msg.attach(MIMEText(mail_content, 'text', 'utf8')) #設定文本正文
attachment =MIMEApplication(open('D:/123.txt', 'rb').read()) #rb郵件以二進制的形式打開
attachment.add_header('Conternt-Disposition','attachment', filename = '123.txt') #在郵件的頭部顯示郵件是有附件的
msg.attach(attachment) #附件附加在郵件中
smtp = SMTP_SSL(host_server)
smtp.login(sender, pwd)
smtp.quit()
uj5u.com熱心網友回復:
我剛完成了一個,費了九牛二虎之力uj5u.com熱心網友回復:
# 生成郵件my_email_from = "運維報表機器人" # 郵箱資訊
my_email_to = '技術部'
# 郵件標題
my_emali_Subject = "資訊采集" + now_time
# 附件正文
my_email_text = "各位領導好:\n\t\t\t\t附件為每日資料報告結果,請查收!\n\n來自報表機器人"
# 附件地址
my__file_path = 'C:/Users/Administrator/Desktop/自動化編程/' + workbook_new
# 附件名稱
my_msg = create_email(my_email_from, my_email_to, my_emali_Subject, my_email_text, my__file_path, workbook_new)
# 發送郵件
my_sender = "[email protected]"
my_password = "xxxxxxxxxxx"
my_receiver = ["xxxxxxxxx.com","aaaaaaaa.com","bbbbbbbbbbbb.com","cccccccccccc.com"]
#呼叫發送郵件的函式
send_mail(my_sender, my_password, my_receiver, my_msg)
def create_email(emali_from, email_to, email_Subject, email_text, file_path, send_file_name):
# 輸入發件人的昵稱,收件人的昵稱,主題,正文,附件地址,附件名稱生成一封郵件
message = MIMEMultipart()
# 將正文以text的形式插入到郵件中
message.attach(MIMEText(email_text, 'plain', 'utf-8'))
# 生成發件人名稱(這個跟發送的郵件沒什么關系)
message['from'] = Header(emali_from, 'utf-8')
# 生成收件人名稱(這個跟接收的郵件也沒有關系)
message['to'] = Header(email_to, 'utf-8')
# 生成郵件的主題
message['Subject'] = Header(email_Subject, 'utf-8')
# 讀取附件的內容
att1 = MIMEText(open(file_path, 'rb').read(), 'base64', 'gbk')
att1["Content-type"] = 'application/octet-stream'
# 生成附件的名稱
# att1["Content-Disposition"] = 'attachment; filename=' + send_file_name
att1.add_header('Content-Disposition', 'attachment', filename=send_file_name)
# 將附件插入郵件中
message.attach(att1)
return message
def send_mail(sender, password, receiver, msg):
# 一個輸入郵箱,密碼,收件人,郵件內容發送的函式
try:
# 找到你的發送郵箱的服務器地址,以加密的形式發送
server = smtplib.SMTP_SSL("smtp.qq.com", 465) # 發件人郵箱中的smtp服務器
server.ehlo()
# 登陸你的賬號
server.login(sender, password) # 括號中對應的是發件人郵箱賬號,郵箱密碼
# 發送郵件
server.sendmail(sender, receiver, msg.as_string())
# 括號中對應的是發件人的郵箱賬號,收件人的郵箱賬號(是一個串列),郵件內容
print("自動郵件發送成功....")
server.quit()
except Exception as e:
print(traceback.print_exc())
print("郵件發送失敗.....")
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/110752.html
上一篇:求教python問題
