key='郵件授權碼'
import smtplib
import ssl
from email.message import EmailMessage
EMAIL_ADDRESS='********@qq.com'
EMAIL_PASSWORD=key
smtp=smtplib.SMTP('smtp.qq.com',25)
context=ssl.create_default_context()
sender=EMAIL_ADDRESS
receiver=EMAIL_ADDRESS
subject="python email subject"
body="Hello,this is an email sent by python!"
msg=EmailMessage()
msg['subject']=subject
msg['From']=sender
msg['To']=receiver
msg.set_content(body)
file_name='附件名字'
with open(file_name,'rb') as f:
file_data=f.read()
msg.add_attachment(file_data,maintype='image',subtype='png',filename=file_name) #按要求修改,此次是附帶圖片
with smtplib.SMTP_SSL("smtp.qq.com",465,context=context) as smtp:
smtp.login(EMAIL_ADDRESS,EMAIL_PASSWORD)
smtp.send_message(msg)
發送郵件測試報告HTML格式的
key='授權碼'
import smtplib
import ssl
from email.message import EmailMessage
EMAIL_ADDRESS='***********@qq.com'
EMAIL_PASSWORD=key
smtp=smtplib.SMTP('smtp.qq.com',25)
context=ssl.create_default_context()
sender=EMAIL_ADDRESS
receiver=EMAIL_ADDRESS
subject="python email subject"
body="Hello,this is an email sent by python!"
msg=EmailMessage()
msg['subject']=subject
msg['From']=sender
msg['To']=receiver
msg.set_content(body)
msg.add_alternative(
"""\
<!DOCTYPE html>
<html>
<body>
<h1 >This 我is an email sent by Python</h1>
</body>
</html>
""",subtype='html'
)
#msg.add_attachment(file_data,maintype='image',subtype='png',filename=file_name)
with smtplib.SMTP_SSL("smtp.qq.com",465,context=context) as smtp:
smtp.login(EMAIL_ADDRESS,EMAIL_PASSWORD)
smtp.send_message(msg)
配置給多個用戶發郵件
key='*************'
import smtplib
import ssl
from email.message import EmailMessage
EMAIL_ADDRESS='********@qq.com'
EMAIL_PASSWORD=key
smtp=smtplib.SMTP('smtp.qq.com',25)
context=ssl.create_default_context()
sender=EMAIL_ADDRESS
receiver=EMAIL_ADDRESS
subject="python email subject"
body="Hello,this is an email sent by python!"
msg=EmailMessage()
msg['subject']=subject
msg['From']=sender
msg['To']=[receiver,*****@qq.com,****@qq.com] #多個用戶
msg.set_content(body)
with smtplib.SMTP_SSL("smtp.qq.com",465,context=context) as smtp:
smtp.login(EMAIL_ADDRESS,EMAIL_PASSWORD)
smtp.send_message(msg)