Книга: Automate the Boring Stuff with Python: Practical Programming for Total Beginners
Назад: 15. Keeping Time, Scheduling Tasks, and Launching Programs
Дальше: 17. Manipulating Images

.

, , MY_SECRET_PASSWORD, and are just placeholders. This code is just an overview of the process of sending email with Python.

lists some common email providers and their SMTP servers. (The port is an integer value and will almost always be 587, which is used by the command encryption standard, TLS.)

for detailed directions on how to set up an application-specific password for your Google account.

Pass a string of your email address as the first argument and a string of your password as the second argument. The 235 in the return value means authentication was successful. Python will raise an smtplib.SMTPAuthenticationError exception for incorrect passwords.

.

.

The imapclient module downloads emails from an IMAP server in a rather complicated format. Most likely, you’ll want to convert them from this format into simple string values. The pyzmail module does the hard job of parsing these email messages for you. You can find the complete documentation for PyzMail at .

Install imapclient and pyzmail from a Terminal window. Appendix A has steps on how to install third-party modules.

lists the IMAP servers for several popular email providers.

.

describes the various search keys.

.

'BEFORE date', 'ON date', 'SINCE date'

These three search keys return, respectively, messages that were received by the IMAP server before, on, or after the given date. The date must be formatted like 05-Jul-2015. Also, while 'SINCE 05-Jul-2015' will match messages on and after July 5, 'BEFORE 05-Jul-2015' will match only messages before July 5 but not on July 5 itself.

'SUBJECT string', 'BODY string', 'TEXT string'

Returns messages where string is found in the subject, body, or either, respectively. If string has spaces in it, then enclose it with double quotes: 'TEXT "search with spaces"'.). Note that some email providers, such as Gmail, automatically expunge emails.

'DRAFT', 'UNDRAFT'

Returns all messages with and without the \Draft flag, respectively. Draft messages are usually kept in a separate Drafts folder rather than in the INBOX folder.

'FLAGGED', 'UNFLAGGED'

Returns all messages with and without the \Flagged flag, respectively. This flag is usually used to mark email messages as “Important” or “Urgent.”

'LARGER N', 'SMALLER N'

Returns all messages larger or smaller than N bytes, respectively.

'NOT search-key'

Returns the messages that search-key would not have returned.

'OR search-key1 search-key2'

Returns the messages that match either the first or second search-key.

Note that some IMAP servers may have slightly different implementations for how they handle their flags and search keys. It may require some experimentation in the interactive shell to see exactly how they behave.

You can pass multiple IMAP search key strings in the list argument to the search() method. The messages returned are the ones that match all the search keys. If you want to match any of the search keys, use the OR search key. For the NOT and OR search keys, one and two complete search keys follow the NOT and OR, respectively.

Here are some example search() method calls along with their meanings:

  • imapObj.search(['ALL']). Returns every message in the currently selected folder.

  • imapObj.search(['ON 05-Jul-2015']). Returns every message sent on July 5, 2015.

  • imapObj.search(['SINCE 01-Jan-2015', 'BEFORE 01-Feb-2015', 'UNSEEN']).  sent since the start of 2015.

  • imapObj.search(['SINCE 01-Jan-2015', 'NOT FROM [email protected]']). Returns every message sent from everyone except since the start of 2015.

  • imapObj.search(['OR FROM [email protected] FROM [email protected]']). Returns every message ever sent from or .

  • imapObj.search(['FROM [email protected]', 'FROM [email protected]']). Trick example! This search will never return any messages, because messages must match all search keywords. Since there can be only one “from” address, it is impossible for a message to be from both and .

The search() method doesn’t return the emails themselves but rather unique IDs (UIDs) for the emails, as integer values. You can then pass these UIDs to the fetch() method to obtain the email content.

Continue the interactive shell example by entering the following:

.

for more information). If you are logging in to a Gmail account, pass the search terms to the gmail_search() method instead of the search() method, like in the following interactive shell example:

whenever you need to remember all of the steps.

for working with Excel files.)

  • Create a dictionary of members who are behind on their dues.

  • Log in to an SMTP server by calling smtplib.SMTP(), ehlo(), starttls(), and login().

  • For all members behind on their dues, send a personalized reminder email by calling the sendmail() method.

  • Open a new file editor window and save it as sendDuesReminders.py.

    and is in a file named duesRecords.xlsx. You can download this file from .

    for more information on accessing cells in Excel spreadsheet files with the openpyxl module.) Enter the following code into the file editor window:

    .

    for more information.

    and fill out the sign-up form. Once you’ve signed up for a new account, you’ll need to verify a mobile phone number that you want to send texts to. (This verification is necessary to prevent people from using the service to spam random phone numbers with text messages.)

    After receiving the text with the verification number, enter it into the Twilio website to prove that you own the mobile phone you are verifying. You will now be able to send texts to this phone number using the twilio module.

    Twilio provides your trial account with a phone number to use as the sender of text messages. You will need two more pieces of information: your account SID and the auth (authentication) token. You can find this information on the Dashboard page when you are logged in to your Twilio account. These values act as your Twilio username and password when logging in from a Python program.

    .

    showed you how to use the requests module to scrape data from . Write a program that runs just before you wake up in the morning and checks whether it’s raining that day. If so, have the program text you a reminder to pack an umbrella before leaving the house.

    ) to check for any instance where the word unsubscribe occurs within an HTML link tag.

    Once you have a list of these URLs, you can use webbrowser.open() to automatically open all of these links in a browser.

    You’ll still have to manually go through and complete any additional steps to unsubscribe yourself from these lists. In most cases, this involves clicking a link to confirm.

    But this script saves you from having to go through all of your emails looking for unsubscribe links. You can then pass this script along to your friends so they can run it on their email accounts. (Just make sure your email password isn’t hardcoded in the source code!)

    covers how to launch programs on your computer using the subprocess.Popen() function. For example, the following call would launch the qBittorrent program, along with a torrent file:

    ) to write a text file log that you can check if errors come up.

    qBittorrent (as well as other BitTorrent applications) has a feature where it can quit automatically after the download completes. explains how you can determine when a launched application has quit with the wait() method for Popen objects. The wait() method call will block until qBittorrent has stopped, and then your program can email or text you a notification that the download has completed.

    There are a lot of possible features you could add to this project. If you get stuck, you can download an example implementation of this program from .

    © RuTLib.com 2015-2018