如何在Python中发送邮件

在我们的博客中, 记录了我们在开发过程中所使用的技术和遇到的问题, 希望作为其他开发和设计者的一个学习交流平台.

如何在Python中发送邮件


使用python发送邮件有以下几种情况:

  • 纯文本的邮件
  • 带附件的邮件
  • 其他邮件

首先我们使用virtualenv创建环境:

    $ virtualenv env
    $ env/bin/pip install wheezy.core

纯文本邮件

直接上代码:

    # plain.py
    from wheezy.core.mail import MailMessage
    from wheezy.core.mail import SMTPClient


    mail = MailMessage(
        subject='Welcome to Python',
        content='Hello World!',
        from_addr='someone@dev.local',
        to_addrs=['you@dev.local'])

    client = SMTPClient()
    client.send(mail)

然后使用以下命令发送:

    python plain.py

如果需要发送HTML的邮件的话, 只需要将content换成HTML, 将content_type设置成'text/html', 设置charset即可:

    from wheezy.core.mail import MailMessage
    from wheezy.core.mail import SMTPClient


    content = """\
    <html><body>
        <h1>Hello World!</h1>
    </body></html>"""
    mail = MailMessage(
        subject='Welcome to Python',
        content=content,
        content_type='text/html',
        charset='utf-8',
        from_addr='someone@dev.local',
        to_addrs=['you@dev.local'])

    client = SMTPClient()
    client.send(mail)

另外, 还可以设置SMTPClient的host, port, tls, credentials等.

带附件的邮件

    # attachment.py
    from wheezy.core.mail import Attachment
    from wheezy.core.mail import MailMessage
    from wheezy.core.mail import SMTPClient


    mail = MailMessage(
        subject='Welcome to Python',
        content='Hello World!',
        from_addr='someone@dev.local',
        to_addrs=['you@dev.local'])
    mail.attachments.append(Attachment(
        name='welcome.txt',
        content='Hello World!'))

    client = SMTPClient()
    client.send(mail)

可以使用factory方法Attachment.from_file从本地文件创建一个附件

其他邮件

我们下载python的logo作为邮件:

    import os.path

    from wheezy.core.mail import Alternative
    from wheezy.core.mail import MailMessage
    from wheezy.core.mail import Related
    from wheezy.core.mail import SMTPClient


    mail = MailMessage(
        subject='Welcome to Python',
        content='Hello World!',
        from_addr='someone@dev.local',
        to_addrs=['you@dev.local'])

    alt = Alternative("""\
    <html><body>
        <h1>Hello World!</h1>
        <p><img src="cid:python-logo.gif" /></p>
    </body></html>""", content_type='text/html')

    curdir = os.path.dirname(__file__)
    path = os.path.join(curdir, 'python-logo.gif')
    alt.related.append(Related.from_file(path))

    mail.alternatives.append(alt)

    client = SMTPClient()
    client.send(mail)

原文链接: http://weiguda.com/blog/56/