Django/Python发送邮件

本文介绍了如何在Python中使用标准库如smtplib、poplib和imaplib进行邮件发送,以及如何利用Django的EmailMultiAlternatives发送包含HTML内容和图片的邮件,同时展示了如何处理图片附件的添加和发送过程。
摘要由CSDN通过智能技术生成

Python标准库 smtplib、poplib、imaplib 是对应协议的实现。

POP3 发送邮件

import poplib
from email.parser import Parser
from utils import print_info
import settings
 
 
# 连接到POP3服务器:
server = poplib.POP3(settings.pop3_server)
# 身份认证:
server.user(settings.email)
server.pass_(settings.password)
 
# stat()返回邮件数量和占用空间:
print('Messages: %s. Size: %s' % server.stat())
# list()返回所有邮件的编号:
resp, mails, octets = server.list()
# 可以查看返回的列表类似[b'1 82923', b'2 2184', ...]
 
# 获取最新一封邮件, 注意索引号从1开始:
latest_mail_index = len(mails)
resp, lines, octets = server.retr(latest_mail_index)
 
# lines存储了邮件的原始文本的每一行,
# 可以获得整个邮件的原始文本:
msg_content = b'\r\n'.join(lines).decode('utf-8')
# 稍后解析出邮件:
msg = Parser().parsestr(msg_content)
print_info(msg)
# 邮件索引号直接从服务器删除邮件
# server.dele(index)
# 关闭连接:
server.quit()

Python中是如何发送邮件的参考如下地址:
https://blog.csdn.net/lvsehaiyang1993/article/details/80731697
https://www.cnblogs.com/zhangxinqi/p/9113859.html
https://blog.csdn.net/qq_35867759/article/details/85613505
1.采用Django中的EmailMultiAlternatives发送html邮件,使用MIMEImage嵌入图片到邮件中。

from email.mime.image import MIMEImage
from django.core.mail import EmailMultiAlternatives
 
#拼接css
content_html = '''<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<head>
    <title>Vinta</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2 user-scalable = yes">
    <style>
      table {
        border-top: 1px solid #ccc;
        border-left: 1px solid #ccc;
      }
      table td, table th {
        border-bottom: 1px solid #ccc;
        border-right: 1px solid #ccc;
        padding: 3px 5px;
      }
      table th {
        background-color: #f1f1f1;
        border-bottom: 2px solid #ccc;
        text-align: center;
      }
      
    </style>
</head>
    <body>
        <p>第一张图片:</p>
        <img src="http://127.0.0.1:8000/auditImg/20220124/423f427f652645c2857fde98ecfed101.png" style="max-width:100%;" contenteditable="false"/>
        <table border="0" width="100%" cellpadding="0" cellspacing="0”>
	        <tbody>
		        <tr>
			        <th>test1</th>
			        <th>test2</th>
			        <th>test3</th>
			        <th>test4</th>
		        </tr>
		        <tr>
			        <td>hhhhh1</td>
			        <td>hhhhh1</td>
			        <td>hhhhh1</td>
			        <td>hhhhh1</td>
		        </tr>
	        </tbody>
        </table>
        <p>第二张图片:</p>
        <img src="http://127.0.0.1:8000/auditImg/auditImg/20220124/e31b5d429e7b4a8793052eb6879f135c.png" style="max-width:100%;" contenteditable="false"/>
    </body>
</html>'''
 
def sendEmail(subject,content_html,from_email,to,cc)
    msg = EmailMultiAlternatives(subject = subject,body = content_html, from_email = from_email, to = to, cc = cc)
 
    msg.attach_alternative(content_html, "text/html")
 
    #处理html中的图片
    #由于保存的图片地址是http://127.0.0.1:8000/auditImg/20211021/2322211.png
    #真实的图片保存路径为static/img/detail/20211021/2322211.png     
    #所以需要转换一下路径,拿到图片地址 
    content_html =content_html.replace('src="http://127.0.0.1:8000/auditImg/','src="cid:')
    
    imgList = re.findall('src="cid:(.*?)"', html_content, re.S)
    print('imgList_____',imgList)
    for img in imgList:
        imgPath = os.path.join('static/img/detail',img)
        print(imgPath)
        image = add_img(imgPath,img)
        # msg.attach(image)
 
    try:
        msg.send()
    except Exception as e:
        print('send_mail exec error'+str(e))
 
 
def add_img(src, img_id):
    with open(src, 'rb') as f:
        msg_image = MIMEImage(f.read())
    msg_image.add_header('Content-ID', img_id)
    return msg_image

2.采用Python发送html邮件,嵌入图片,并添加附件。

 
import smtplib
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart 
 
sender = 'xxxxxx.com'        #发送邮箱
receivers = [''xxxxxxx.com]   #接受邮箱
 
message = MIMEMultipart('related')          #采用related定义内嵌资源的邮件体
message['Subject'] = '邮件标题。。。。。'
message['From'] = sender
message['To'] = ','.join(receivers)
 
#html内容
#拼接css
html_css_head = '''<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<head>
    <style>
      table {
        border-top: 1px solid #ccc;
        border-left: 1px solid #ccc;
      }
      table td, table th {
        border-bottom: 1px solid #ccc;
        border-right: 1px solid #ccc;
        padding: 3px 5px;
      }
      table th {
        background-color: #f1f1f1;
        border-bottom: 2px solid #ccc;
        text-align: center;
      }      
    </style>
</head>
<body>
<div id="content">'''
 
html_css_footer = '''</div></body></html>'''
mail_msg = """
<p>Python 邮件发送测试...</p>
<p><a href="http://www.runoob.com">这是一个链接</a></p>
<p>图片演示:</p>
<p><img src="cid:image1"></p>
<p>表格演示:</p>
<table>
<tr><th>第一列</th><th>第二列</th><th>第三列</th><th>第四列</th></tr>
<tr><td>h1</td><td>h2</td><td>h3</td><td>h4</td></tr>
<tr><td>d1</td><td>d2</td><td>d3</td><td>d4</td></tr>
</table>
"""
mail_msg = html_css_head + mail_msg + html_css_footer
msgtext = MIMEText(mail_msg,_subtype='html',_charset='utf-8')   #_subtype有plain,html等格式,避免使用错误
message.attach(msgtext)
 
# 指定图片为当前目录
fp = open('img.png', 'rb')
msgImage = MIMEImage(fp.read())
fp.close()
 
# 定义图片 ID,在 HTML 文本中引用
msgImage.add_header('Content-ID', '<image1>')
message.attach(msgImage)
 
#添加附件
filename = 'file.xlsx'
attachment='/Users/mac/Desktop/file.xlsx'
att1 = MIMEApplication(open(attachment, 'rb').read())
att1.add_header('Content-Disposition', 'attachment', filename=('gbk', '', filename))  #注意:此处basename要转换为gbk编码,否则中文会有乱码。 
message.attach(att1)
 
#发送邮件
try:
    smtpObj = smtplib.SMTP('mail host',25)
    smtpObj.login("用户名","密码")
    smtpObj.sendmail(sender, receivers, message.as_string())
    print("邮件发送成功")
except smtplib.SMTPException:
    print("Error: 无法发送邮件")```


  • 8
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值