一、QQ設置
打開QQ郵箱設置(以QQ爲例)
- 進入帳戶
- 第二步,開啓服務,並且生成授權碼
二、python代碼
1. 第一種發送方式
借用smtplib;ssl 協議安全發送 smtplib.SMTP_SSL(host=smtpServer,port=commonPort)
;smtp的sendmail發送郵件;MIMEText的主要作用是用來規範內容類型的,比如是文本,還是圖像等。
步驟:
- 第一步:主題,類似標題
subject = "主題"
- 第二步:發送內容
content = "內容"
- 第三步:發送人
sender = "發送人@163.com"
- 第四步:接收人
rec ="可以是單個,可以是多個"
- 第五步:授權碼
password = "授權碼"
- 第六步:實例化MIMEText,參數說明,第一個是要發送的內容,第二個是內容的類型,第三個是編碼類型
- 第七步:將主題,發件人,收件人寫入
- 第八步:登陸郵箱併發送郵件
smtp = smtplib.SMTP_SSL("smtp.163.com",465)
參數以什麼郵箱發送,端口號 - 第九步:登陸
smtp.login(sender,password)
參數,發送人和授權碼 - 第十步:發送郵件
smtp.sendmail(sender,rec.split(",\n"),message.as_string())
參數:發送人,接收人,發送郵件,要轉換成類似json格式
代碼實現:
import smtplib
from email.mime.text import MIMEText
## 主題
subject = "主題"
# 發送內容
content = "Good Good study,day day up"
# 發送人
sender = "發送人@163.com"
# 接收人 單個 多個收件人
rec = """[email protected],
[email protected],
[email protected],
[email protected]
"""
password = "授權碼"
### MIMEText 參數 發送內容, 內容類型 , 編碼
message = MIMEText(content,"plain","utf-8")
message["Subject"] = subject
message["From"] = sender ## 發件人
message["To"] = rec ## 收件人
### 發送郵件
smtp = smtplib.SMTP_SSL("smtp.163.com",465)
## smtp = smtplib.SMTP_SSL("smtp.qq.com",25)
smtp.login(sender,password)
## 參數說明 發件人 收件人需要一個列表 發送郵件 類似一種json的格式
smtp.sendmail(sender,rec.split(",\n"),message.as_string())
smtp.close()
要注意的是QQ郵箱端口號必須要用25
2. 第二種發送方式
- settings六步配置
EMAIL_HOST = 'smtp.xxx.com' #郵件服務器地址
EMAIL_PORT = xx #端口號25 or 465
EMAIL_HOST_USER = '[email protected]' #你的郵箱
EMAIL_HOST_PASSWORD = 'xxxx' #授權碼
EMAIL_USE_TLS = True #默認,不是True發送不成功
EMAIL_FROM = 'xxxx' # 你的郵箱
- python代碼:
from django.core.mail import send_mail
email_title = '郵件標題'
email_body = '郵件內容'
email = '[email protected]' #對方的郵箱
send_status = send_mail(email_title, email_body, EMAIL_FROM, [email])