使用django发送电子邮件

时间:2013-03-19 05:26:07

标签: django email django-views

在我的项目中,可以使用电子邮件ID字段。

我正在收集作者的电子邮件ID,在更新数据库中的详细信息时,应该发送一封电子邮件给该特定的电子邮件ID,说明书名已更新。

我的views.py是

def addbook(请求):

log.debug("test....")

form = BookForm

if request.POST:
    form = BookForm(request.POST)
    if form.is_valid():
        cd = form.cleaned_data
        send_mail(cd['book_name'],cd['author_name'],cd.get(''),['to@example.com'],)
        form.save()
        return redirect('/index/')
return render_to_response('addbook.html',{ 'form':form },context_instance=RequestContext(request))

我正在使用此send_mail()方法来执行该操作,但它无法正常工作。

models.py是

class Book(models.Model):

book_id=models.AutoField(primary_key=True,unique=True)
book_name=models.CharField(max_length=30)
author_name=models.CharField(max_length=30)
publisher_name=models.CharField(max_length=40)
email = models.EmailField()
bookref = models.CharField(max_length=10)
class Meta:
    db_table = u'Book'

def __unicode__(self):
    return "%d %s %s %s %s" % (self.book_id,self.book_name, self.author_name,self.publisher_name,self.email,self.bookref)

forms.py

class BookForm(ModelForm):

    log.debug("test....")

    class Meta:
        model = Book

        fields=['book_id','book_name','author_name','publisher_name','email','bookref']

邮件应发送到电子邮件字段中提到的电子邮件ID。

由于

1 个答案:

答案 0 :(得分:4)

<强> settings.py

EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'user'
EMAIL_HOST_PASSWORD = 'password'
DEFAULT_FROM_EMAIL = 'your email'

<强> views.py

if request.POST:
    form = BookForm(request.POST)
    if form.is_valid():
        cd = form.cleaned_data

        email_to = cd['email']
        subject = "{0} Update".format(
            cd['book_name'])
        message = "Author: {0}\n\n Your book name is updated".format(
            cd['author_name'])
        send_mail(subject, message, settings.DEFAULT_FROM_EMAIL,[email_to,])

        form.save()
        return redirect('/index/')