封装了Django的send_mail函数,方便在localhost进行邮件相关的测试

作者:半瓶墨水   链接:http://www.2maomao.com/blog/django-localhost-mail-test/

最近在为发芽网添加一些邮件通知功能
由于本地没有邮件服务器,在发邮件的那段代码就会产生异常
虽然在发生异常时仍可以通过Debug=True来看本地变量的值,但是这样毕竟很不爽

很多天以前在Python-cn讨论组问过这个问题,其中Leo Jay和Zoom Quiet的回答很不错,提出根据server的地址或者端口来判断,本地一般不是80端口,而且一般是127.0.0.1,所以比较好判断

这样就可以封一个mock,本地自动采用print打出来,Server端则可以正常收发Email

最近工作太忙,直到今日才有时间实现,代码如下:

Python语言: 封装Django的send_mail函数,方便在本地(没有邮件服务器)进行邮件相关的测试
def my_send_mail(request, subject, body, sender, recv_list, reply_to=None):
    ""”send_mail wrapper: write to command line if it's called on localhost
    ""”
    local = "127.0.0.1"
    if request.META['HTTP_HOST'][:len(local)] == local:
        print "Subject:", subject
        print "From:", sender
        print "To:", recv_list
        if reply_to:
            print "Reply-To:", reply_to
        print "Body:\n", body
    else:
        if reply_to:
            email = EmailMessage(
                        subject,
                        body,
                        sender,
                        recv_list,
                        [],
                        headers = {'Reply-To': reply_to})
            email.send()
        else:
            send_mail(subject, body, sender, recv_list)

留下回复