Django联系表单发送邮件到我自己的邮箱

aiqt4smr  于 2023-04-07  发布在  Go
关注(0)|答案(2)|浏览(137)

views.py

def contact(request):
    if request.method == "POST":
        username    =   request.POST['username']
        phone       =   request.POST['phone']
        customer_email  =   request.POST['customer_email']
        subject     =   request.POST['subject']
        message     =   request.POST['message']

        #send Email
        send_mail(subject, message, customer_email, ['myemail@gmail.com'])

        return render(request, 'contact.html', {'username': username })

    else:
        return render(request, 'contact.html', {})

这是我的html

<form method="post" action="{% url 'contact' %}" id="contact-form">
  {% csrf_token %}
  <div class="row clearfix">
    <div class="col-lg-6 col-md-6 col-sm-12 form-group">
      <input type="text" name="username" placeholder="Name" required="">
    </div>

    <div class="col-lg-6 col-md-6 col-sm-12 form-group">
      <input type="text" name="phone" placeholder="Phone" required="">
    </div>

    <div class="col-lg-6 col-md-6 col-sm-12 form-group">
      <input type="email" name="customer_email" placeholder="Email" required="">
    </div>

    <div class="col-lg-6 col-md-6 col-sm-12 form-group">
      <input type="text" name="subject" placeholder="Subject" required="">
    </div>

    <div class="col-lg-12 col-md-12 col-sm-12 form-group">
      <textarea name="message" placeholder="Message"></textarea>
    </div>

    <div class="col-lg-12 col-md-12 col-sm-12 form-group">
      <button class="theme-btn btn-style-one" type="submit" name="submit-form">Submit Now</button>
    </div>
  </div>
</form>

这是我应该发送电子邮件到customer_email的表单,但我却收到了电子邮件。也就是说,发件人和收件人都是相同的。这里有什么问题?还有,是否可以在电子邮件中添加客户的电子邮件和电话号码?

o2rvlv0m

o2rvlv0m1#

send_mail的文档说:

send_mail(subject, message, from_email, recipient_list, ...)

所以当你打电话

send_mail(subject, message, customer_email, ['myemail@gmail.com'])

你把customer_email插入到from_email,把你的电子邮件地址插入到recipient_list......所以,是的,你得到了电子邮件,因为你告诉计算机这样做。
或许:

username = request.POST['username']
phone = request.POST['phone']
customer_email = request.POST['customer_email']
subject = request.POST['subject']
message = request.POST['message']

content = f"""
{message}

Username: {username}
Phone: {phone}
Email: {customer_email}
"""

send_mail(
  subject=subject,
  message=content,
  from_email=None,  # use default sender from settings
  recipient_list=[customer_email],
)

只是要小心垃圾邮件-一个开放的联系表格,这样很容易得到你的地址或服务器在世界各地封锁,因为你基本上允许任何人使用它发送消息给任何人。

ua4mk5z4

ua4mk5z42#

如果要将邮件存储在数据库中,还需要设计邮件模型。

相关问题