python3 發郵件 smtplib & email 庫


 嗨 實現了用163發送到qq的功能,遺留了兩個問題:

1. 接收者list會報錯;
update:因為list[]會傳遞過去一個真的[]list,改成如下就可以了:
before:
  maillist=['a@qq.com','b@qq.com'] msg['To']=maillist print (maillist) -->['a@qq.com', 'b@qq.com'] after: maillist = ['a@qq.com','b@qq.com'] msg['To'] = ','.join(maillist) print(maillist) --> a@qq.com,b@qq.com

 


2. msg.as_string() 是什么意思?
update:就是把msg轉成string了


揍是不想google了啊喂,感覺最近google越來越查不到想要的答案了。
update:還是得繼續google下去,繼續求問下去啊,另外,官方英文文檔看了也看不懂,囧了個囧

 

 

貼上部分代碼,方便懶人copy:

def sendmail(subject, content):
    email_host = 'smtp.163.com'     # 發送者是163郵箱
    email_user = '發送者郵箱賬號,我用漢字替換掉'  # 發送者賬號
    email_pwd = '發送者郵箱密碼,我用漢字替換掉'       # 發送者密碼
    maillist ='接收者郵箱賬號,我用漢字替換掉'    # 接收者賬號,本來想寫成[]list的,但是報錯,還沒解決!
    me = email_user
    # 三個參數:第一個為文本內容,第二個 html 設置文本格式,第三個 utf-8 設置編碼
    msg = MIMEText(content, 'html', 'utf-8')    # 郵件內容
    msg['Subject'] = subject    # 郵件主題
    msg['From'] = me    # 發送者賬號
    msg['To'] = maillist    # 接收者賬號列表(列表沒實現)

    smtp = smtplib.SMTP(email_host) # 如上變量定義的,是163郵箱
    smtp.login(email_user, email_pwd)   # 發送者的郵箱賬號,密碼
    smtp.sendmail(me, maillist, msg.as_string())    # 參數分別是發送者,接收者,第三個不知道
    smtp.quit() # 發送完畢后退出smtp
    print ('email send success.')


sendmail('主題', '內容')    # 調用發送郵箱的函數

還有第二種方法也實現了,不過我喜歡上面那種,是loveisbug寫的,感覺很程序

第二種是從網上找的,作者忘了,真忘了,昨天搜的

import smtplib
import email.mime.multipart
import email.mime.text

msg = email.mime.multipart.MIMEMultipart()
msg['from'] = '發送者的郵箱賬號'
msg['to'] = '接收者的郵箱賬號'
msg['subject'] = 'test,這是郵件主題'
content = '''''
    你好,
            這是一封自動發送的郵件的內容。
'''
txt = email.mime.text.MIMEText(content)
msg.attach(txt)

smtp = smtplib
smtp = smtplib.SMTP()
smtp.connect('smtp.163.com') # 使用的發送者郵箱的那啥來着,post
smtp.login('發送者的郵箱賬號', '發送者的郵箱密碼')
smtp.sendmail('發送者的郵箱賬號', '接收者的郵箱賬號', str(msg))
smtp.quit()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM