`
dixian
  • 浏览: 15712 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

Python - Sending Email

阅读更多

Python - Sending Email using SMTP

Simple Mail Transfer Protocol (SMTP) is a protocol which handles sending e-mail and routing e-mail between mail servers.

Python provides smtplib module which defines an SMTP client session object that can be used to send mail to any Internet machine with an SMTP or ESMTP listener daemon.

Here is a simple syntax to create one SMTP object which can later be used to send an email:

import smtplib

smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )

Here is the detail of the parameters:

  • host: This is the host running your SMTP server. You can specifiy IP address of the host or a domain name like tutorialspoint.com. This is optional argument.

  • port: If you are providing host argument then you need to specifiy a port where SMTP server is listening. Usually this port would be 25.

  • local_hostname: If your SMTP server is running on your local machine then you can specify just localhost as of this option.

An SMTP object has an instance method called sendmail, which will typically be used to do the work of mailing a message. It takes three parameters:

  • The sender - A string with the address of the sender.

  • The receivers - A list of strings, one for each recipient.

  • The message - A message as a string formatted as specified in the various RFCs.

Example:

Here is a simple way to send one email using Python script. Try it once:

#!/usr/bin/python

import smtplib

sender = 'from@fromdomain.com'
receivers = ['to@todomain.com']

message = """From: From Person <from@fromdomain.com>
To: To Person <to@todomain.com>
Subject: SMTP e-mail test

This is a test e-mail message.
"""

try:
   smtpObj = smtplib.SMTP('localhost')
   smtpObj.sendmail(sender, receivers, message)         
   print "Successfully sent email"
except SMTPException:
   print "Error: unable to send email"

 Here you have placed a basic e-mail in message, using a triple quote, taking care to format the headers correctly. An e-mails requires a From, To, and Subject header, separated from the body of the e-mail with a blank line.

To send the mail you use smtpObj to connect to the SMTP server on the local machine and then use the sendmail method along with the message, the from address, and the destination address as parameters (even though the from and to addresses are within the e-mail itself, these aren't always used to route mail).

If you're not running an SMTP server on your local machine, you can use smtplib client to communicate with a remote SMTP server. Unless you're using a webmail service (such as Hotmail or Yahoo! Mail), your e-mail provider will have provided you with outgoing mail server details that you can supply them, as follows:

smtplib.SMTP('mail.your-domain.com', 25)

 Sending an HTML email using Python:

When you send a text message using Python then all the content will be treated as simple text. Even if you will include HTML tags in a text message, it will be displayed as simple text and HTML tags will not be formatted according to HTML syntax. But Python provides option to send an HTML message as actual HTML message.

While sending an email message you can specify a Mime version, content type and character set to send an HTML email. 

 Example:

 Following is the example to send HTML content as an email. Try it once:

 

#!/usr/bin/python

import smtplib

message = """From: From Person <from@fromdomain.com>
To: To Person <to@todomain.com>
MIME-Version: 1.0
Content-type: text/html
Subject: SMTP HTML e-mail test

This is an e-mail message to be sent in HTML format

<b>This is HTML message.</b>
<h1>This is headline.</h1>
"""

try:
   smtpObj = smtplib.SMTP('localhost')
   smtpObj.sendmail(sender, receivers, message)         
   print "Successfully sent email"
except SMTPException:
   print "Error: unable to send email"

 Sending Attachements as an e-mail:  

To send an email with mixed content requires to set Content-type header to multipart/mixed. Then text and attachment sections can be specified within boundaries.

A boundary is started with two hyphens followed by a unique number which can not appear in the message part of the email. A final boundary denoting the email's final section must also end with two hyphens.

Attached files should be encoded with the pack("m") function to have base64 encoding before transmission.

Example:

Following is the example which will send a file /tmp/test.txt as an attachment. Try it once:

#!/usr/bin/python

import smtplib
import base64

filename = "/tmp/test.txt"

# Read a file and encode it into base64 format
fo = open(filename, "rb")
filecontent = fo.read()
encodedcontent = base64.b64encode(filecontent)  # base64

sender = 'webmaster@tutorialpoint.com'
reciever = 'amrood.admin@gmail.com'

marker = "AUNIQUEMARKER"

body ="""
This is a test email to send an attachement.
"""
# Define the main headers.
part1 = """From: From Person <me@fromdomain.net>
To: To Person <amrood.admin@gmail.com>
Subject: Sending Attachement
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=%s
--%s
""" % (marker, marker)

# Define the message action
part2 = """Content-Type: text/plain
Content-Transfer-Encoding:8bit

%s
--%s
""" % (body,marker)

# Define the attachment section
part3 = """Content-Type: multipart/mixed; name=\"%s\"
Content-Transfer-Encoding:base64
Content-Disposition: attachment; filename=%s

%s
--%s--
""" %(filename, filename, encodedcontent, marker)
message = part1 + part2 + part3

try:
   smtpObj = smtplib.SMTP('localhost')
   smtpObj.sendmail(sender, reciever, message)
   print "Successfully sent email"
except Exception:
   print "Error: unable to send email" 
分享到:
评论

相关推荐

    Python Network Programming Cookbook, 2nd Edition - 2017

    sending emails from a script or creating a guest book for your web application. We learn to write email clients with SMTP and POP3. Chapter 6, Programming Across Machine Boundaries, gives you a taste ...

    EMAIL-Sending-Project:电子邮件发送项目第6天的分配

    在本项目中,我们关注的是"EMAIL-Sending-Project:电子邮件发送项目第6天的分配",这似乎是一个关于利用编程技术实现自动化电子邮件发送的学习任务或实战项目。在这个项目的第6天,可能涉及到了关键技术和步骤的深化...

    Python库 | mail_sending_program-1.3-py3-none-any.whl

    《Python邮件发送库mail_sending_program详解》 Python作为一种强大且易学的编程语言,在开发领域广泛应用,尤其在后端开发中,Python以其丰富的库资源备受青睐。在众多的Python库中,`mail_sending_program-1.3-py...

    Python库 | awsmailman-0.4.0-py3-none-any.whl

    print('Email sending failed:', response) ``` 以上就是关于`awsmailman-0.4.0-py3-none-any.whl`这个Python库的详细解释,它为开发者提供了一种便捷的方式来利用AWS SES服务发送电子邮件,简化了邮件发送的流程...

    PyPI 官网下载 | mail_sending_program-0.0.4-py3-none-any.whl

    body = "This is a test email sent using the mail_sending_program library." # 创建邮件 message = sender.create_message(sender_email, receiver, subject, body) # 发送邮件 sender.send(message) ``` 以上...

    send-the-data-files-with-email

    在"send-the-data-files-with-email-master"这个项目中,可能包含了实现这个功能的完整示例代码,包括配置、邮件构建和发送的具体步骤。你可以通过查看源代码进一步学习和理解这个过程,以便在自己的项目中灵活运用...

    Python程序设计(第二版).chm

    Programming Python, 2nd Edition 目录如下,需要下载的朋友不要错过哦~ Programming Python, 2nd Edition By Mark Lutz Publisher : O'Reilly Pub Date : March 2001 ISBN : 0-596-00085-5 Pages : 1256 ...

    Automate.the.Boring.Stuff.with.Python.Practical.Programming

    Sending Email and Text Messages Chapter 17. Manipulating Images Chapter 18. Controlling the Keyboard and Mouse with GUI Automation Appendix A. Installing Third-Party Modules Appendix B. Running ...

    Python Cookbook, 2nd Edition

    Sending Binary Data to Standard Output Under Windows Recipe 2.13. Using a C++-like iostream Syntax Recipe 2.14. Rewinding an Input File to the Beginning Recipe 2.15. Adapting a File-like Object...

    Python网络编程.pdf

    ### Python网络编程知识点详解 #### 一、简介 随着互联网技术的发展,“网络编程”已成为软件开发领域中的一个热点话题。目前市场上的应用软件中有超过一半是面向网络的应用,如数据库服务器、游戏、Java Servlets...

    简单的python信号_Python_下载.zip

    print(f'Sending welcome email to user {user_id}') ``` 4. **参数传递** 信号可以携带参数,这些参数可以在接收器中访问。在上面的例子中,`user_registered`信号携带了`user_id`参数。接收器可以直接访问...

    templatemail:适用于Python的模板化电子邮件

    mailgun# Credentials for MailgunMAILGUN_API_KEY = 'YOUR API KEY'MAILGUN_DOMAIN = 'MAILGUN_DOMAIN'# The engine is in charge of sending email using a backend system.engine = templatemail . engines . ...

    Camelishing:社会工程工具

    1-Bulk email sending 2-Basic Python Agent Creator 3-Office Excel Macro Creator 4-DDE Excel Creator(or Custom Payload) 5-Return İnformation * [Mail Open Track] * [Agent Open Track] 6-AutoSave 7-...

    Fresh Killer COpyright notice sending

    【标题】"Fresh Killer COpyright notice sending"指的是一个名为FreshKiller的程序,它的主要功能是针对那些托管有非法软件副本的网站发送版权通知邮件。这个程序可能是版权保护者或者软件发行商用来维护其知识产权...

    Django docs-1.11-en

    - **Sending email (发送邮件)**: 介绍了 Django 发送邮件的功能。 - **Internationalization and localization (国际化和本地化)**: 详细介绍了如何使应用支持多语言和地域设置。 - **Logging (日志记录)**: 介绍了...

    使用Python实现一个简单的项目监控

    print(f"Error occurred while sending email: {e}") ``` 为了定期执行监控任务,我们可以使用Python的`schedule`库来设置定时任务。首先安装`schedule`库(如果尚未安装): ```bash pip install schedule ``` ...

    mailService:基于python3的邮件服务。提供邮件模板系统、多语言邮件、自动翻译、多邮件服务器管理以及微型web api示例。 Mail service based on python3. Provide mail template system, multi-language, automatic translation, multi-mail server management and micro web api examples

    简单的: :tangerine: Based on python3, and lightweight :watermelon: Allow to add multiple sending servers, if one server is broken, it will automatically switch to other servers :doughnut: Email ...

    Django documentation(英文版).pdf

    - **Sending email:** 提供了在Django项目中发送电子邮件的指导。 - **Internationalization and localization:** 讲述了如何为Django应用添加国际化支持,使其支持多语言。 - **Logging:** 解释了如何在Django应用...

    scrapy1.6.pdf

    3. **发送邮件(Sending Email):** - **定义:**通过配置邮件发送功能,在爬虫结束时发送通知邮件。 - **配置方法:** - 设置MAIL_HOST、MAIL_USER等配置项。 - **示例配置:** ```python MAIL_HOST = 'smtp....

Global site tag (gtag.js) - Google Analytics