开发者

Keeping DRY with sending mail in Django

I have the following two blocks of code in a LOT of my views. Im looking for a way to abstract them so that instead of repeating this code in every view. The receipent, subject line and body will vary of course, so I would like to be able to pass those strings to this function--"function" is the right term to use, correct?

mailt = loader.get_template('membership/signup_email.txt')
mailc = Context({
    'signin_url': signin_url,
    'name': firstname + ' ' + lastname,
    'username': username,
    'membership_level': membership_level.name,
    'membership_number': membership_number,
    'payment_plan': payment_plan
})
msg = EmailMessage(
    'You are now a Member!',
    mailt.render(mailc),
    'membership@domain.org',
    [email]
)
msg.content_subtype = "html"
msg.send()

# Nofity our staff
admin_mailt = loader.get_template('membership/signup_admin_email开发者_JAVA百科.txt')
admin_mailc = Context({
    'site': current_site,
    'user': user,
    'payment_plan': payment_plan
})
admin_msg = EmailMessage(
    '[myproject] New Membership Signup',
    admin_mailt.render(admin_mailc),
    'membership@domain.org',
    ['membership@domain.org']
)
admin_msg.content_subtype = "html"
admin_msg.send()


I'm not sure where your variables are all coming from...but....could you simply create a function in say a utils.py? Put the above code in there and call it with parameters when needed. So your views might have something like follows. A call to a function you created elsewhere.

custom_send_mail(recipient, subject, body)


You could use the built in django email methods and abstract them a little to get what you want, it won't buy you that much, but here you go.

See the documentation here: http://docs.djangoproject.com/en/1.3/topics/email/

Here is how you use the built in django email method.

from django.core.mail import send_mail

send_mail('Subject here', 'Here is the message.', 'from@example.com',
    ['to@example.com'], fail_silently=False)

So one of your examples above would turn into this.

# Nofity our staff
admin_mailt = loader.get_template('membership/signup_admin_email.txt')
admin_mailc = Context({
    'site': current_site,
    'user': user,
    'payment_plan': payment_plan
})

send_mail('[myproject] New Membership Signup', admin_mailt.render(admin_mailc), 'membership@domain.org', ['membership@domain.org'])

You could wrap this a little so that you could just pass in the template name and the context and it would make it a little cleaner.

send_my_email(subject, to_address, template, context, from_address='membership@domain.org'):
    admin_mailt = loader.get_template(template)
    send_mail(subject, admin_mailt.render(context), from_address, to_address)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜