Django发送电子邮件并从html输入字段获取收件人电子邮件

M.I*_*zat 0 html python django

我有一个django方法来发送电子邮件。当前电子邮件收件人已在代码中进行了硬编码,如何动态创建一个从html页面提交字段的位置,它将立即获取收件人电子邮件并执行该方法

HTML

<input id="recipient_email" type="email">
Run Code Online (Sandbox Code Playgroud)

view.py

from django.core.mail import EmailMultiAlternatives

def send_email(subject, text_content, html_content, to):
    to = 'test_to@gmail.com'
    from_email = 'test_from@gmail.com'
    subject = 'New Project Created'
    text_content = 'A Test'
    html_content = """
        <h3 style="color: #0b9ac4>email received!</h3>
    """
    email_body = html_content
    msg = EmailMultiAlternatives(subject, text_content, from_email, to)
    msg.attach_alternative(email_body, "text/html")
    msg.send()
Run Code Online (Sandbox Code Playgroud)

Vit*_*tas 5

您需要在视图中进行工作。另外,为了将数据发送到服务器,您需要给输入名称

<input id="recipient_email" type="email" name="recipient_email_address">
Run Code Online (Sandbox Code Playgroud)

然后,在Django视图中,您将获得以下输入数据:

如果是POST请求:

to = request.POST['recipient_email_address']
Run Code Online (Sandbox Code Playgroud)

如果是GET请求:

to = request.GET['recipient_email_address']
Run Code Online (Sandbox Code Playgroud)

然后,您将to变量作为参数传递给send_email函数。

请注意,期望中的to参数是EmailMultiAlternativesa list而不是a str

参见以下示例:

index.html

<form method="post">
  {% csrf_token %}
  <input id="recipient_email" type="email" name="recipient_email_address">
  <button type="submit">Submit</button>
</form>
Run Code Online (Sandbox Code Playgroud)

views.py

def send_email_view(request):
    if request.method == 'POST':
        to = request.POST['recipient_email_address']
        send_email('subject of the message', 'email body', '<p>email body</p>', [to, ])
    return render(request, 'index.html')
Run Code Online (Sandbox Code Playgroud)

处理用户输入时,请考虑使用Forms API。在文档中阅读有关它的更多信息