我有一个django方法来发送电子邮件。目前电子邮件收件人在代码中是硬编码的,如何动态创建从html页面提交字段的位置,它会立即获取收件人电子邮件并执行方法
HTML
<input id="recipient_email" type="email">
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()
答案 0 :(得分:4)
您需要在视图中完成工作。另外,为了将数据发送到服务器,您需要为输入提供名称。
<input id="recipient_email" type="email" name="recipient_email_address">
然后,在Django视图中,您将得到如下输入数据:
如果是 POST 请求:
to = request.POST['recipient_email_address']
如果是 GET 请求:
to = request.GET['recipient_email_address']
然后您将to
变量作为参数传递给send_email
函数。
请注意,to
中的EmailMultiAlternatives
参数需要list
,而不是str
。
见下面的例子:
<强>的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 强>
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')
在处理用户输入时,请考虑使用Forms API。 Read more about it in the documentation