Tabla de contenido
2. Enviar contenido de mensaje de texto sin formato:
3. Enviar contenido en formato HTML:
4. Envíe un correo electrónico con un archivo adjunto:
5. Envío masivo (enviar un correo electrónico a varias personas):
enviar correo electrónico
Los siguientes ejemplos utilizan el buzón QQ como remitente;
1. Trabajos de preparación:
Para utilizar el buzón QQ para enviar correos electrónicos, debe ir a " Configuración " => " Cuenta " para habilitar el servicio POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV :
Después de iniciar el servicio, haga clic en Administrar servicio :
Luego saltará a la página de cuenta y seguridad, hará clic en Generar código de autorización para generar el código de autorización y registrará el código de autorización:
referencia:
https://wx.mail.qq.com/list/readtemplate?name=app_intro.html#/agreement/authorizationCode
2. Enviar contenido de mensaje de texto sin formato:
import smtplib
import time
from email.mime.text import MIMEText
def send_QQ_email_plain():
sender = user = '[email protected]' # 发送方的邮箱账号
passwd = 'abcdefgxxxxx' # 授权码
receiver = '[email protected]' # 接收方的邮箱账号,不一定是QQ邮箱
# 纯文本内容
msg = MIMEText(f'Python 邮件发送测试 {time.time()}', 'plain', 'utf-8')
# From 的内容是有要求的,前面的abc为自己定义的 nickname,如果是ASCII格式,则可以直接写
msg['From'] = f'abc <[email protected]>'
msg['To'] = receiver
msg['Subject'] = 'Python SMTP 邮件测试' # 点开详情后的标题
try:
# 建立 SMTP 、SSL 的连接,连接发送方的邮箱服务器
smtp = smtplib.SMTP_SSL('smtp.qq.com', 465)
# 登录发送方的邮箱账号
smtp.login(user, passwd)
# 发送邮件 发送方,接收方,发送的内容
smtp.sendmail(sender, receiver, msg.as_string())
print('邮件发送成功')
smtp.quit()
except Exception as e:
print(e)
print('发送邮件失败')
Requisitos para mensaje['Formulario']:
Si el apodo personalizado es un carácter que no es ASCII, se informará un error si se escribe directamente, como por ejemplo:
msg['From'] = f'好 <[email protected]>'
El formato correcto es:
msg['From'] = f'=?UTF-8?B?{base64.b64encode("好".encode()).decode()}?= <[email protected]>'
Si el destinatario es un buzón QQ, el apodo anterior se mostrará en esta posición:
Si no necesita definir su propio apodo, también puede utilizar su cuenta de correo electrónico directamente:
msg['From'] = '[email protected]'
Se mostrará la cuenta de correo electrónico:
Haga clic en el correo electrónico para ver los detalles:
3. Enviar contenido en formato HTML:
import base64
import smtplib
import time
from email.mime.text import MIMEText
def send_QQ_mail_HTML():
user = '[email protected]'
passwd = 'abcdefxxxx'
receiver = '[email protected]'
# 直接写
# html_content = '''
# <h1>这个是邮件的内容</h1>
# '''
# 读入 html 文件的内容
with open('./for_email.html', mode='r', encoding='utf-8') as f:
html_content = f.read()
# 指定类型是 html
msg = MIMEText(html_content, 'html', 'utf-8')
msg['From'] = user
msg['To'] = receiver
msg['Subject'] = '测试发送 HTML 内容'
try:
smtp = smtplib.SMTP_SSL('smtp.qq.com', 465)
smtp.login(user, passwd)
smtp.sendmail(user, receiver, msg.as_string())
print('发送成功')
except:
print('发送失败')
Contenido de for_email.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
h1{
color: brown;
}
p{
margin: 5px;
color: purple;
}
</style>
</head>
<body>
<h1>这是一个邮件内容的标头</h1>
<img src="https://img1.baidu.com/it/u=1890390320,3399874998&fm=253&fmt=auto&app=120&f=JPEG?w=1422&h=800">
<div>
<h3>From合法性检查</h3>
<p>一、根据RFC5322协议,邮件标头中需要包含'From'信息。</p>
<p>二、根据RFC2047, RFC822协议,邮件标头中的'From'形式为:</p>
<p>1. 邮箱地址形式:prefix@domain, 如 '[email protected]'。</p>
<p>2. 昵称+空格+<邮箱地址>形式:nickname <prefix@domain>,其中,nickname为ASCII字符集中字符组合或编码文本:</p>
<p>(1)如果昵称全为ASCII字符,如'ABC',邮箱地址为'[email protected]',则标头中的'From'为'ABC <[email protected]>'。
注意'ABC'和'<[email protected]>'之间用空格隔开;</p>
<p>(2)如果昵称包含非ASCII字符,如中文,则请使用base64对昵称进行编码。nickname最终的形式为
:"=?" charset "?" encoding "?" encoded-text "?="。其中,charset为字符集;
encoding为编码方式,'B'代表base64;encoded-text为编码后的文本。例如,昵称为'QQ邮箱昵称示例',
邮箱地址为'[email protected]',则对昵称进行base64编码,字符集使用UTF-8,则
nickname为 '=?UTF-8?B?UVHpgq7nrrHmmLXnp7DnpLrkvos=?=',最终邮件标头中的
'From'为'"=?utf-8?B?UVHpgq7nrrHmmLXnp7DnpLrkvos=?=" <[email protected]>'。
注意编码文本和邮件地址间用空格隔开。</p>
</div>
</body>
</html>
El html contiene imágenes img que hacen referencia a enlaces externos. Si el destinatario es un buzón QQ, las imágenes no se mostrarán de forma predeterminada:
Si se trata de otro buzón, es posible que se muestre la imagen (como el buzón corporativo de WeChat) y que el estilo html se pierda y resulte ineficaz.
4. Envíe un correo electrónico con un archivo adjunto:
import base64
import smtplib
import time
from email.mime.application import MIMEApplication
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def send_QQ_email_mul():
sender = user = '[email protected]'
passwd = 'abcdefghijk' # 不是密码,是生成的 授权码
receiver = '[email protected]'
content = MIMEMultipart() # 创建一个包含多个部分的内容
content['From'] = user
content['To'] = receiver
content['Subject'] = 'Test Email'
# 添加文本内容
# text = MIMEText('this is a test email.', 'plain', 'utf-8')
# content.attach(text)
# 添加html内容
with open('./for_email.html', mode='r', encoding='utf-8') as f:
html_content = f.read()
msg = MIMEText(html_content, 'html', 'utf-8')
content.attach(msg)
# 添加附件
with open('./data.xlsx', 'rb') as f:
attachment = MIMEApplication(f.read()) # 读取为附件
attachment.add_header('Content-Disposition', 'attachment', filename='data.xlsx')
content.attach(attachment)
try:
smtp = smtplib.SMTP_SSL('smtp.qq.com', 465)
smtp.login(user, passwd)
smtp.sendmail(sender, receiver, content.as_string())
print('邮件发送成功')
except Exception as e:
print(e)
print('发送邮件失败')
5. Envío masivo (enviar un correo electrónico a varias personas):
Simplemente escriba el destinatario como una matriz de la cuenta de correo electrónico de cada persona.
import base64
import smtplib
import time
from email.mime.text import MIMEText
def send_QQ_mail():
sender = user = '[email protected]'
passwd = 'ABCD'
# 写成数组,将发给这三者
receiver = ['[email protected]','[email protected]','[email protected]']
msg = MIMEText(f'Python 邮件发送测试 {time.time()}', 'plain', 'utf-8')
msg['From'] = f'=?UTF-8?B?{base64.b64encode("好".encode()).decode()}?= <[email protected]>'
msg['To'] = 'you' # 每个人都会看到这个内容
msg['Subject'] = 'Python SMTP 邮件测试' # 点开详情后的标题
try:
# 建立 SMTP 、SSL 的连接
smtp = smtplib.SMTP_SSL('smtp.qq.com', 465)
# 登录
smtp.login(user, passwd)
# 发送邮件 发送方,接收方,发送的内容
smtp.sendmail(sender, receiver, msg.as_string())
print('邮件发送成功')
smtp.quit()
except Exception as e:
print(e)
print('发送邮件失败')