准备工作
- host
- user
- pass
smtp.qq.com
3335215292@qq.com
授权码 syw....vthtk....
smtplib库
发送邮件
import smtplib
from email.mime.text import MIMEText
from email.header import Header
# 第三方SMTP服务
mail_host = 'smtp.qq.com'
mail_user = '3335215292@qq.com'
mail_pass = '----'
"""
发送者与接收者
"""
send_user = '3335215292@qq.com'
receive_user = ['569781231@qq.com']
msg = MIMEText('这是一封邮件','plain','utf-8') #发送的内容
msg['From'] = Header('桃阿','utf-8') # 发件人
msg['to'] = Header('569781231@qq.com','utf-8') # 收件人
msg['Subject'] = Header('Python SMTP 邮件测试','utf-8') #邮件的主题
try:
server = smtplib.SMTP(mail_host,587) #主机地址与端口
server.starttls()
server.login(mail_user, mail_pass) # 登陆
server.sendmail(send_user,receive_user,msg.as_string()) #发送人 收件人 发送消息
print('邮件发送成功')
server.quit()
except Exception as e:
print(e)
login()
方法用来登录SMTP服务器sendmail()
方法就是发邮件- 邮件正文是一个str,
as_string()
把MIMEText对象变成str
发送带有HTML格式的邮件
在构造MIMEText对象时,把HTML字符串传进去,再把第二个参数由plain变为html就可以了
import smtplib
from email.mime.text import MIMEText
from email.header import Header
# 第三方SMTP服务
mail_host = 'smtp.qq.com'
mail_user = '3335215292@qq.com'
mail_pass = '----'
send_user = '3335215292@qq.com'
receive_user = ['569781231@qq.com']
mail_msg = """
<h1 style="color:red;">今天天气真好</h1>
<a href="http://www.baodu.com" target="_blank">百度</a>
<hr/>
"""
msg = MIMEText(mail_msg,'html','utf-8') #这里选择文本 HTML格式发送 编码格式
msg['From'] = Header('桃阿','utf-8') # 发件人
msg['to'] = Header('569781231@qq.com','utf-8') # 收件人
subject = 'Python HTML格式邮件'
msg['Subject'] = Header(subject,'utf-8') #邮件的主题
try:
server = smtplib.SMTP(mail_host,587)
server.starttls()
server.login(mail_user, mail_pass) # 登陆
server.sendmail(send_user, receive_user, msg.as_string()) # 发送
print('邮件发送成功')
server.quit()
except Exception as e:
print(e)
使用Django发送邮件
发送文本
#配置settings.py
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.qq.com' #发送方的smtp服务器地址
EMAIL_PORT = 25 #smtp服务端口,默认为25
EMAIL_HOST_USER = '3335215292@qq.com' #发送服务器的用户名
EMAIL_HOST_PASSWORD = '----' #用户的密码
# 新建send_mial.py
import os
from django.core.mail import send_mail
os.environ['DJANGO_SETTINGS_MODULE'] = 'AG02.settings'
if __name__ == '__main__':
send_mail(
'测试邮件', #邮件主题
'欢迎访问主内容区域', #邮件具体内容
'3335215292@qq.com', #邮件发送方
['569781231@qq.com'], #接受方的邮件地址列表
fail_silently=False
)
发送HTML格式的邮件
import os
from django.core.mail import send_mail
from django.core.mail import EmailMultiAlternatives
os.environ['DJANGO_SETTINGS_MODULE'] = 'AG02.settings'
if __name__ == '__main__':
subject, from_email,to_email = '测试邮件','3335215292@qq.com',['569781231@qq.com']
html_con = """
<h1 style='color:red;'>Yo Friend</h1>
"""
# subject主题 content内容 to_addr是一个列表 发送给那些人
msg = EmailMultiAlternatives(subject,html_con,from_email, to_email)
#类型
msg.content_subtype = 'html'
# 发送
msg.send()