首页 > 解决方案 > 在 html 正文中发送带有图像的电子邮件 - Django

问题描述

我知道网站上有这样的问题,但没有一个能够回答我的困难。所以我有如下代码:

# custom_methods.py

from django.core.mail import EmailMultiAlternatives
from django.conf import settings

from pathlib import Path
from email.mime.image import MIMEImage

import threading, random, os

class EmailThread(threading.Thread):
    def __init__(self, subject, body, from_email, recipient_list, fail_silently, html):
        self.subject = subject
        self.body = body
        self.from_email = from_email
        self.recipient_list = recipient_list
        self.fail_silently = fail_silently
        self.html = html
        threading.Thread.__init__(self)

    def run(self):
        msg = EmailMultiAlternatives(self.subject, self.body, self.from_email, self.recipient_list)
        image_path = os.path.join(settings.BASE_DIR, '/static/images/instagram_icon.png')
        image_name = Path(image_path).name
        if self.html:
            msg.attach_alternative(self.html, "text/html")
            msg.content_subtype = 'html'
            msg.mixed_subtype = 'related'

            with open(image_path, 'rb') as f:
                image = MIMEImage(f.read())
                image.add_header('Content-ID', f"<{image_name}>")
                msg.attach(image)
        msg.send(self.fail_silently)

def send_mail(subject, recipient_list, body='', from_email=settings.EMAIL_HOST_USER, fail_silently=False, html=None, *args, **kwargs):
    EmailThread(subject, body, from_email, recipient_list, fail_silently, html).start()
# views.py

class UserRegisterView(CreateView):
    model = User
    form_class = CustomUserCreationForm
    template_name = 'accounts/register.html'

    def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.is_active = False
        self.object.save()
        send_mail(
            subject=f'{self.object.code} is your Instagram code',
            recipient_list=[self.object.email],
            html=render_to_string('accounts/register_email.html', {
                'email':self.object.email,
                'code':self.object.code,
            })
        )
        return redirect('accounts:login')
# register_email.html - This is the html that is connected to the email that will be sent

{% load static %}
{% load inlinecss %}

{% inlinecss "css/email.css" %}
<img src="cid:{image_name}">                    

<h1>Hi,</h1>
<h2>Someone tried to sign up for an Instagram account with {{ email }}. If it was you, enter this confirmation code in the app:</h2>
<h2>{{ code }}</h2>
{% endinlinecss %}

所以假设会发生以下情况:

  1. 注册用户
  2. 用户注册后,会使用上面显示的 html 模板向用户发送一封电子邮件。

现在一切正常,但是当我注册用户时出现问题,并且在 Powershell 中,弹出以下错误:

with open(image_path, 'rb') as f:
FileNotFoundError: [Errno 2] No such file or directory: 'C:/static/images/instagram_icon.png'

当然在 中找不到图片'C:/static/images/instagram_icon.png',因为图片的绝对目录会在'C:Users/...(and so on).../static/images/instagram_icon.png'. 那么如何在开发阶段解决这个问题呢?我找不到这个问题的答案,有人可以帮忙吗??

标签: pythondjangoemail

解决方案


推荐阅读