简体   繁体   English

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

[英]Django sending email and get the recipient email from html input field

I have a django method to send an email. 我有一个django方法来发送电子邮件。 currently the email recipient is hardcoded in the code, how can I create a dynamically where on submit a field from html page it will immediately get the recipient email and execute the method 当前电子邮件收件人已在代码中进行了硬编码,我如何动态创建一个从html页面提交字段的地方,它将立即获取收件人电子邮件并执行该方法

Html HTML

<input id="recipient_email" type="email">

view.py 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()

You need to do the work inside a view. 您需要在视图中进行工作。 Also, in order to send data to the server, you need to give a name to the input. 另外,为了将数据发送到服务器,您需要给输入名称

<input id="recipient_email" type="email" name="recipient_email_address">

Then, inside a Django view, you would get this input data like this: 然后,在Django视图中,您将获得以下输入数据:

If it was a POST request: 如果是POST请求:

to = request.POST['recipient_email_address']

If it was a GET request: 如果是GET请求:

to = request.GET['recipient_email_address']

Then you would pass the to variable as an argument to your send_email function. 然后,将to变量作为参数传递给send_email函数。

Please note that the to argument in the EmailMultiAlternatives expects a list , instead of a str . 请注意, EmailMultiAlternatives中的to参数需要一个list ,而不是str

See below an example: 参见以下示例:

index.html index.html

<form method="post">
  {% csrf_token %}
  <input id="recipient_email" type="email" name="recipient_email_address">
  <button type="submit">Submit</button>
</form>

views.py 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')

Please consider using the Forms API when dealing with user input. 处理用户输入时,请考虑使用Forms API。 Read more about it in the documentation . 在文档中阅读有关它的更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM