2

So I have a form on my web application in which I am trying to collect feedback from users. The form consists of a subject, email, and the content and I want the emails to be sent to my account. I am having a lot of verification and understanding trouble with this. My code is below and I will further explain my problem afterwards.

Settings.py

EMAIL_HOST_USER and EMAIL_HOST_PASSWORD are filled on my app.

EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"

EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587

EMAIL_HOST_USER = '#'
EMAIL_HOST_PASSWORD = '#'

EMAIL_USE_TLS = True
EMAIL_USE_SSL = False

Forms.py

class Contact(forms.Form):
    subject = forms.CharField(required=True)
    content = forms.CharField(widget=forms.Textarea)
    email = forms.EmailField(required=True)

Views.py

def about(request):
    if request.method == 'GET':
        form = Contact()
    else:
        form = Contact(request.POST)
        if form.is_valid():
            subject = form.cleaned_data['subject']
            content = form.cleaned_data['content']
            email = ['contacttexchange@gmail.com']


            #try:
            server = smtplib.SMTP('smtp.gmail.com:587')
            server.starttls()
            server.login(settings.EMAIL_HOST_USER, settings.EMAIL_HOST_PASSWORD)
            server.sendmail(email, email, content)
            server.quit()
            print "Successfully sent email"
        #except SMTPException:
            print "Error: unable to send email"

So I am a little bit confused as to how I can send an e-mail from a users account to mine as I would have to get the user to sign in so currently I am trying to send an e-mail from my account to my account and I was just going to append the users e-mail to the content. However this is not working either.

One, is sending e-mails to myself a stupid way of doing it?

Also, regarding the code problem I keep getting verification errors and google says I should setup two way verification. Is this what I should be doing?

Could someone give me some ideas as to where I should be heading? Thanks.

ForceBru
  • 43,482
  • 10
  • 63
  • 98
Programmingjoe
  • 2,169
  • 2
  • 26
  • 46
  • 1
    Sending stuff through gmail is a bit peculiar. Check out this other SO question: http://stackoverflow.com/questions/25944883/how-to-send-an-email-through-gmail-without-enabling-insecure-access – spectras Oct 06 '15 at 17:31
  • use smtp server from mailgun.com or similar service. Up to 10 000 send mails a month its free. – Lucas03 Oct 06 '15 at 21:09

1 Answers1

0

Firstly, allow access to app from your gmail account provided you will get the mail when you will try this code and you have to allow access and don't allow 2-step verification Use the code given below :

forms.py

from flask_wtf import Form
from wtforms import StringField, TextAreaField, SubmitField, validators

class ContactForm(Form):
name = StringField('Your Name:', [validators.DataRequired()])
email = StringField('Your e-mail address:', [validators.DataRequired(), validators.Email('your@email.com')])
message = TextAreaField('Your message:', [validators.DataRequired()])
submit = SubmitField('Send Message')

contact.html

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Contact</title>
</head>
<body>
<h1>Contact Form:</h1>

<form action="/contact" method="post">
      {{ form.hidden_tag() }}
    <p>
      {{ form.name.label }}
      {{ form.name }}
    </p>
    <p>
      {{ form.email.label }}
      {{ form.email }}
    </p>
    <p>
      {{ form.message.label }}
      {{ form.message }}
    </p>
    <p>
      {{ form.submit }}
    </p>
  </form>
  </body>
  </html>

main.py

from flask import Flask, render_template, request
from flask_mail import Mail, Message
from forms import ContactForm


app = Flask(__name__)
app.secret_key = 'YourSuperSecreteKey'

# add mail server config
app.config['MAIL_SERVER'] = 'smtp.gmail.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USE_SSL'] = True
app.config['MAIL_USERNAME'] = 'YourUser@NameHere'
app.config['MAIL_PASSWORD'] = 'yourMailPassword'

mail = Mail(app)

@app.route('/contact', methods=('GET', 'POST'))
def contact():
form = ContactForm()

if request.method == 'POST':
    if form.validate() == False:
        return 'Please fill in all fields <p><a href="/contact">Try Again!!! </a></p>'
    else:
        msg = Message("Message from your visitor" + form.name.data,
                      sender='YourUser@NameHere',
                      recipients=['yourRecieve@mail.com', 'someOther@mail.com'])
        msg.body = """
        From: %s <%s>,
        %s
        """ % (form.name.data, form.email.data, form.message.data)
        mail.send(msg)
        return "Successfully  sent message!"
elif request.method == 'GET':
    return render_template('contact.html', form=form)

if __name__ == '__main__':
app.run()