首页 > 其他分享 >发邮件

发邮件

时间:2022-11-28 19:45:01浏览次数:70  
标签:qq 发邮件 发送 mail message com 邮件

目录

Python发邮件

这里以QQ邮箱为例,首先要拿到授权码,这里登录你的QQ邮箱,在设置中,选择账号选项,下拉到POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务项,获取授权码。

发送普通文本邮件

import smtplib
from email.mime.text import MIMEText
from email.header import Header

# 第三方 SMTP 服务
mail_host = "smtp.qq.com"  # 设置服务器
mail_user = "[email protected]"  # 用户名
mail_pass = "dfpcglacrjbybafa"  # 获取授权码
sender = '[email protected]'  # 发件人账号
receivers = ['[email protected]']  # 接收邮件,可设置为你的QQ邮箱或者其他邮箱
send_content = 'Python 邮件发送测试...'
message = MIMEText(send_content, 'plain', 'utf-8')  # 第一个参数为邮件内容,第二个设置文本格式,第三个设置编码
message['From'] = Header("我是发件人", 'utf-8')  # 发件人
message['To'] = Header("我是收件人", 'utf-8')   # 收件人

subject = '邮件大标题'
message['Subject'] = Header(subject, 'utf-8')
try:
    smtpObj = smtplib.SMTP()
    smtpObj.connect(mail_host, 25)  # 25 为 SMTP 端口号
    smtpObj.login(mail_user, mail_pass)
    smtpObj.sendmail(sender, receivers, message.as_string())
    print("邮件发送成功")
except smtplib.SMTPException:
    print("Error: 无法发送邮件")

发送HTML格式邮件

import smtplib
from email.mime.text import MIMEText
from email.header import Header

# 第三方 SMTP 服务
mail_host = "smtp.qq.com"  # 设置服务器
mail_user = "[email protected]"  # 用户名
mail_pass = "dfpcglacrjbybafa"  # 口令

sender = '[email protected]'
receivers = ['[email protected]']  # 接收邮件,可设置为你的QQ邮箱或者其他邮箱
send_content = """
<h1>天不生我李淳罡</h1>
<h1>剑道万古如长夜</h1>
<p>小二上酒</p>
<img src="https://ss0.baidu.com/73t1bjeh1BF3odCf/it/u=858168512,2130327819&fm=85&s=2E4020DF1CD035FBDC9D940A0300F0F3">
<div>阅读请&nbsp;<a href="https://www.37zw.net/0/761/">点我,点我</a></div>
"""
message = MIMEText(send_content, 'html', 'utf-8')  # 第一个参数为邮件内容
message['From'] = Header("我是发件人", 'utf-8')  # 发件人
message['To'] = Header("我是收件人", 'utf-8')  # 收件人

subject = '雪中悍刀行'
message['Subject'] = Header(subject, 'utf-8')

try:
    smtpObj = smtplib.SMTP()
    smtpObj.connect(mail_host, 25)  # 25 为 SMTP 端口号
    smtpObj.login(mail_user, mail_pass)
    smtpObj.sendmail(sender, receivers, message.as_string())
    print("邮件发送成功")

except smtplib.SMTPException:
    print("Error: 无法发送邮件")

发送HTML中带本地图片的邮件

上一个示例中的图片,是一个远程连接,那么我们要发送本地的图片,就要采用下面的方式了:

import smtplib
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.header import Header

# 第三方 SMTP 服务
mail_host = "smtp.qq.com"  # 设置服务器
mail_user = "[email protected]"  # 用户名
mail_pass = "dfpcglacrjbybafa"  # 口令

sender = '[email protected]'
receivers = ['[email protected]']  # 接收邮件,可设置为你的QQ邮箱或者其他邮箱

message = MIMEMultipart('related')
message['From'] = Header("我是发件人", 'utf-8')  # 发件人
message['To'] = Header("我是收件人", 'utf-8')  # 收件人

subject = '雪中悍刀行--本地图片版'
message['Subject'] = Header(subject, 'utf-8')

msg = MIMEMultipart('alternative')
message.attach(msg)


send_content = """
<h1>天不生我李淳罡</h1>
<h1>剑道万古如长夜</h1>
<p>小二上酒</p>
<img src="cid:image">
<div>阅读请&nbsp;<a href="https://www.37zw.net/0/761/">点我,点我</a></div>
"""
msg.attach(MIMEText(send_content, 'html', 'utf-8'))  # 第一个参数为邮件内容

# 读取当前目录下的图片
f = open('img.jpg', 'rb')
img_msg = MIMEImage(f.read())
f.close()

# 定义图片在HTML文本中的位置
img_msg.add_header('Content-ID', '<image>')   # 根据id定位
message.attach(img_msg)


try:
    smtpObj = smtplib.SMTP()
    smtpObj.connect(mail_host, 25)  # 25 为 SMTP 端口号
    smtpObj.login(mail_user, mail_pass)
    smtpObj.sendmail(sender, receivers, message.as_string())
    print("邮件发送成功")

except smtplib.SMTPException:
    print("Error: 无法发送邮件")

发送带各式类型附件的邮件

发送带附件的邮件,首先要创建MIMEMultipart实例,然后在构建附件,如果有多个附件的话,可依次构建,最后利用smtplib.smtp发送:

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header

# 第三方 SMTP 服务
mail_host = "smtp.qq.com"  # 设置服务器
mail_user = "[email protected]"  # 用户名
mail_pass = "dfpcglacrjbybafa"  # 口令

sender = '[email protected]'
receivers = ['[email protected]']  # 接收邮件,可设置为你的QQ邮箱或者其他邮箱
# 创建一个带附件的实例
message = MIMEMultipart()
message['From'] = Header("我是发件人", 'utf-8')  # 发件人
message['To'] = Header("我是收件人", 'utf-8')   # 收件人

subject = 'Python发送带附件的邮件示例'
message['Subject'] = Header(subject, 'utf-8')

# 邮件正文内容
send_content = 'hi man,你收到附件了吗?'
content_obj = MIMEText(send_content, 'plain', 'utf-8')  # 第一个参数为邮件内容
message.attach(content_obj)

# 构造附件1,发送当前目录下的 t1.txt 文件
att1 = MIMEText(open('t1.txt', 'rb').read(), 'base64', 'utf-8')
att1["Content-Type"] = 'application/octet-stream'
# 这里的filename可以任意写,写什么名字,邮件附件中显示什么名字
att1["Content-Disposition"] = 'attachment; filename="t1.txt"'
message.attach(att1)

# 构造附件2,发送当前目录下的 t2.py 文件
att2 = MIMEText(open('t2.py', 'rb').read(), 'base64', 'utf-8')
att2["Content-Type"] = 'application/octet-stream'
att2["Content-Disposition"] = 'attachment; filename="t2.py"'
message.attach(att2)
try:
    smtpObj = smtplib.SMTP()
    smtpObj.connect(mail_host, 25)  # 25 为 SMTP 端口号
    smtpObj.login(mail_user, mail_pass)
    smtpObj.sendmail(sender, receivers, message.as_string())
    print("邮件发送成功")

except smtplib.SMTPException:
    print("Error: 无法发送邮件")


如果要发送其他类型的,如果PDF、doc、xls、MP3格式的,我们都可以通过MIMEApplication来完成,MIMEApplication默认子类型是application/octet-stream,而application/octet-stream表明这是个二进制文件,但愿接收方知道怎么处理!!!,然后客户端收到这个声明后会根据文件扩展名来猜测。

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.header import Header

# 第三方 SMTP 服务
mail_host = "smtp.qq.com"  # 设置服务器
mail_user = "[email protected]"  # 用户名
mail_pass = "dfpcglacrjbybafa"  # 口令

sender = '[email protected]'
receivers = ['[email protected]']  # 接收邮件,可设置为你的QQ邮箱或者其他邮箱
# 创建一个带附件的实例
message = MIMEMultipart()
message['From'] = Header("我是发件人", 'utf-8')  # 发件人
message['To'] = Header("我是收件人", 'utf-8')   # 收件人

subject = 'Python发送带附件的邮件示例'
message['Subject'] = Header(subject, 'utf-8')

# 邮件正文内容
send_content = 'hi man,你收到附件了吗?'
content_obj = MIMEText(send_content, 'plain', 'utf-8')  # 第一个参数为邮件内容
message.attach(content_obj)

# 构造附件1,发送当前目录下的 t1.txt 文件
part1 = MIMEApplication(open('t1.txt', 'rb').read())
part1.add_header('Content-Disposition', 'attachment', filename='t1.txt')
message.attach(part1)


# 构造附件2,发送当前目录下的 bg.mp3 文件
part2 = MIMEApplication(open('bg.mp3', 'rb').read())
part2.add_header('Content-Disposition', 'attachment', filename='bg.mp3')
message.attach(part2)


# 构造附件3,发送当前目录下的 t3.xls 文件
part3 = MIMEApplication(open('t3.xls', 'rb').read())
part3.add_header('Content-Disposition', 'attachment', filename='t3.xls')
message.attach(part3)

# 构造附件4,发送当前目录下的 t4.doc 文件
part4 = MIMEApplication(open('t4.doc', 'rb').read())
part4.add_header('Content-Disposition', 'attachment', filename='t4.doc')
message.attach(part4)


# 构造附件5,发送当前目录下的 t5.pdf 文件
part5 = MIMEApplication(open('t5.pdf', 'rb').read())
part5.add_header('Content-Disposition', 'attachment', filename='t5.pdf')
message.attach(part5)

# 构造附件6,发送当前目录下的 img.jpg 文件
part6 = MIMEApplication(open('img.jpg', 'rb').read())
part6.add_header('Content-Disposition', 'attachment', filename='img.jpg')
message.attach(part6)

try:
    smtpObj = smtplib.SMTP()
    smtpObj.connect(mail_host, 25)  # 25 为 SMTP 端口号
    smtpObj.login(mail_user, mail_pass)
    smtpObj.sendmail(sender, receivers, message.as_string())
    print("邮件发送成功")

except smtplib.SMTPException:
    print("Error: 无法发送邮件")

通过smtplib.SMTP_SSL发送邮件

import smtplib
from email.utils import formataddr
from email.mime.text import MIMEText

# 通过smtplib.SMTP_SSL发送邮件
mail_host = "smtp.163.com"  # 网易邮箱服务器
mail_user = "[email protected]"  # 账号
mail_token = "WLWFMHNAYBCARUTP"  # 获取的授权码
sender = "[email protected]"  # 发件人邮件
# 收件人可以写一个
to = "[email protected]"
# 如果是多个收件人,就以列表的形式发送就行了
to_list = ["[email protected]", "[email protected]"]
msg = MIMEText("邮件正文内容", "html", "utf-8")  # # 第一个参数为邮件内容,第二个设置文本格式,第三个设置编码
msg["From"] = formataddr(["张开", sender])
msg['To'] = to
msg["Subject"] = "邮件大标题"

server = smtplib.SMTP_SSL(mail_host)
server.login(mail_user, mail_token)
server.sendmail(mail_user, to_list, msg.as_string())
server.quit()

使用Django内置邮件功能发邮件

发送简单邮件示例

settings.py配置

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = True  # 是否使用TLS安全传输协议(用于在两个通信应用程序之间提供保密性和数据完整性。)
EMAIL_USE_SSL = False  # 是否使用SSL加密,qq企业邮箱要求使用
EMAIL_HOST = 'smtp.163.com'  # 发送邮件的邮箱 的 SMTP服务器,这里用了163邮箱
EMAIL_PORT = 25  # 发件箱的SMTP服务器端口
EMAIL_HOST_USER = '[email protected]'  # 发送邮件的邮箱地址
EMAIL_HOST_PASSWORD = 'xxxxxx'  # 发送邮件的邮箱密码(这里使用的是授权码)
EMAIL_TO_USER_LIST = ['[email protected]', '[email protected]']   # 此字段是可选的,用来配置收件人列表

注意,EMAIL_USE_TLS和EMAIL_USE_SSL是互斥的,也就是说,不能同时为True。

views.py

from django.core.mail import send_mail
def send_email(request):
    send_mail(
        subject='这里是邮件标题',
        message='这里是邮件内容',
        from_email='[email protected]',  # 发件人
        recipient_list=['[email protected]'],  # 收件人
        fail_silently=False   # 如果为False时,发送失败抛出错误
    )
    return HttpResponse('OK')    

多封邮件发送多个收件人

views.py

from django.core.mail import send_mail, send_mass_mail
def send_email(request):
    message1 = ('邮件标题1', '内容1', '[email protected]', ['[email protected]'])
    message2 = ('邮件标题2', '内容2', '[email protected]', ['[email protected]'])
    send_mass_mail((message1, message2), fail_silently=False)
    return HttpResponse('OK')

这里简要说下send_mail和send_mass_mail的区别:

send_mail每次发邮件都会建立一个连接,发多封邮件时建立多个连接。而 send_mass_mail 是建立单个连接发送多封邮件,所以一次性发送多封邮件时 send_mass_mail 要优于 send_mail。

发送带附件的邮件

from django.shortcuts import render, HttpResponse
from django.core.mail import EmailMessage
def send_email(request):
   msg = EmailMessage(
        subject='这是带附件的邮件标题',
        body='这是带附件的邮件内容',
        from_email='[email protected]',  # 也可以从settings中获取
        to=['[email protected]']
    )
    msg.attach_file('t2.xls')
    msg.send(fail_silently=False)
    return HttpResponse('OK')

标签:qq,发邮件,发送,mail,message,com,邮件
From: https://www.cnblogs.com/fuminer/p/16933392.html

相关文章