Package pyzmail :: Module generate
[hide private]
[frames] | no frames]

Module generate

source code

Useful functions to compose and send emails.

For short:

>>> payload, mail_from, rcpt_to, msg_id=compose_mail((u'Me', 'me@foo.com'),
... [(u'Him', 'him@bar.com')], u'the subject', 'iso-8859-1', ('Hello world', 'us-ascii'),
... attachments=[('attached', 'text', 'plain', 'text.txt', 'us-ascii')])
... #doctest: +SKIP
>>> error=send_mail(payload, mail_from, rcpt_to, 'localhost', smtp_port=25)
... #doctest: +SKIP
Functions [hide private]
str
format_addresses(addresses, header_name=None, charset=None)
Convert a list of addresses into a MIME-compliant header for a From, To, Cc, or any other address related field.
source code
inherit from email.Message
build_mail(text, html=None, attachments=[], embeddeds=[])
Generate the core of the email message regarding the parameters.
source code
tuple
complete_mail(message, sender, recipients, subject, default_charset, cc=[], bcc=[], message_id_string=None, date=None, headers=[])
Fill in the From, To, Cc, Subject, Date and Message-Id headers of one existing message regarding the parameters.
source code
tuple
compose_mail(sender, recipients, subject, default_charset, text, html=None, attachments=[], embeddeds=[], cc=[], bcc=[], message_id_string=None, date=None, headers=[])
Compose an email regarding the arguments.
source code
dict
send_mail2(payload, mail_from, rcpt_to, smtp_host, smtp_port=25, smtp_mode='normal', smtp_login=None, smtp_password=None)
Send the message to a SMTP host.
source code
dict or str
send_mail(payload, mail_from, rcpt_to, smtp_host, smtp_port=25, smtp_mode='normal', smtp_login=None, smtp_password=None)
Send the message to a SMTP host.
source code
Variables [hide private]
  __package__ = 'pyzmail'
Function Details [hide private]

format_addresses(addresses, header_name=None, charset=None)

source code 

Convert a list of addresses into a MIME-compliant header for a From, To, Cc, or any other address related field. This mixes the use of email.utils.formataddr() and email.header.Header().

Parameters:
  • addresses (list) - list of addresses, can be a mix of string a tuple of the form [ 'address@domain', (u'Name', 'name@domain'), ...]. If u'Name' contains non us-ascii characters, it must be a unicode string or encoded using the charset argument.
  • header_name (string or None) - the name of the header. Its length is used to limit the length of the first line of the header according the RFC's requirements. (not very important, but it's better to match the requirements when possible)
  • charset (str) - the encoding charset for non unicode name and a hint for encoding of unicode string. In other words, if the name of an address in a byte string containing non us-ascii characters, then name.decode(charset) must generate the expected result. If a unicode string is used instead, charset will be tried to encode the string, if it fail, utf-8 will be used. With Python 3.x charset is no more a hint and an exception will be raised instead of using utf-8 has a fall back.
Returns: str
the encoded list of formated addresses separated by commas, ready to use as Header value.
>>> print format_addresses([('John', 'john@foo.com') ], 'From', 'us-ascii').encode()
John <john@foo.com>
>>> print format_addresses([(u'l\xe9o', 'leo@foo.com') ], 'To', 'iso-8859-1').encode()
=?iso-8859-1?q?l=E9o?= <leo@foo.com>
>>> print format_addresses([(u'l\xe9o', 'leo@foo.com') ], 'To', 'us-ascii').encode() 
... # don't work in 3.X because charset is more than a hint 
... #doctest: +SKIP
=?utf-8?q?l=C3=A9o?= <leo@foo.com>
>>> # because u'léo' cannot be encoded into us-ascii, utf8 is used instead
>>> print format_addresses([('No\xe9', 'noe@f.com'), (u'M\u0101ori', 'maori@b.com')  ], 'Cc', 'iso-8859-1').encode()
... # don't work in 3.X because charset is more than a hint 
... #doctest: +SKIP
=?iso-8859-1?q?No=E9?= <noe@f.com> , =?utf-8?b?TcSBb3Jp?= <maori@b.com>
>>> # 'Noé' is already encoded into iso-8859-1, but u'M\u0101ori' cannot be encoded into iso-8859-1 
>>> # then utf8 is used here
>>> print format_addresses(['a@bar.com', ('John', 'john@foo.com') ], 'From', 'us-ascii').encode()
a@bar.com , John <john@foo.com>

build_mail(text, html=None, attachments=[], embeddeds=[])

source code 

Generate the core of the email message regarding the parameters. The structure of the MIME email may vary, but the general one is as follow:

   multipart/mixed (only if attachments are included)
    |
    +-- multipart/related (only if embedded contents are included) 
    |    |
    |    +-- multipart/alternative (only if text AND html are available)
    |    |    |
    |    |    +-- text/plain (text version of the message)
    |    |    +-- text/html  (html version of the message)
    |    |     
    |    +-- image/gif  (where to include embedded contents)
    |
    +-- application/msword (where to add attachments)
Parameters:
  • text (tuple or None) - the text version of the message, under the form of a tuple: (encoded_content, encoding) where encoded_content is a byte string encoded using encoding. text can be None if the message has no text version.
  • html (tuple or None) - the HTML version of the message, under the form of a tuple: (encoded_content, encoding) where encoded_content is a byte string encoded using encoding html can be None if the message has no HTML version.
  • attachments (list) - the list of attachments to include into the mail, in the form [(data, maintype, subtype, filename, charset), ..] where :
    • data : is the raw data, or a charset encoded string for 'text' content.
    • maintype : is a MIME main type like : 'text', 'image', 'application' ....
    • subtype : is a MIME sub type of the above maintype for example : 'plain', 'png', 'msword' for respectively 'text/plain', 'image/png', 'application/msword'.
    • filename this is the filename of the attachment, it must be a 'us-ascii' string or a tuple of the form (encoding, language, encoded_filename) following the RFC2231 requirement, for example ('iso-8859-1', 'fr', u'r\xe9pertoir.png'.encode('iso-8859-1'))
    • charset : if maintype is 'text', then data must be encoded using this charset. It can be None for non 'text' content.
  • embeddeds (list) - is a list of documents embedded inside the HTML or text version of the message. It is similar to the attachments list, but filename is replaced by content_id that is related to the cid reference into the HTML or text version of the message.
Returns: inherit from email.Message
the message in a MIME object
>>> mail=build_mail(('Hello world', 'us-ascii'), attachments=[('attached', 'text', 'plain', 'text.txt', 'us-ascii')])
>>> mail.set_boundary('===limit1==')
>>> print mail.as_string(unixfrom=False)    
Content-Type: multipart/mixed; boundary="===limit1=="
MIME-Version: 1.0
<BLANKLINE>
--===limit1==
Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
<BLANKLINE>
Hello world
--===limit1==
Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename="text.txt"
<BLANKLINE>
attached
--===limit1==--

complete_mail(message, sender, recipients, subject, default_charset, cc=[], bcc=[], message_id_string=None, date=None, headers=[])

source code 

Fill in the From, To, Cc, Subject, Date and Message-Id headers of one existing message regarding the parameters.

Parameters:
  • message (email.Message) - the message to fill in
  • sender (tuple) - a tuple of the form (u'Sender Name', 'sender.address@domain.com')
  • recipients (list) - a list of addresses. Address can be tuple or string like expected by format_addresses(), for example: [ 'address@dmain.com', (u'Recipient Name', 'recipient.address@domain.com'), ... ]
  • subject (str) - The subject of the message, can be a unicode string or a string encoded using default_charset encoding. Prefert unicode to byte string here.
  • default_charset (str) - The default charset for this email. Arguments that are non unicode string are supposed to be encoded using this charset. This charset will be used has an hint when encoding mail content.
  • cc (list) - The carbone copy addresses. Same format as the recipients argument.
  • bcc (list) - The blind carbone copy addresses. Same format as the recipients argument.
  • message_id_string (str or None) - if None, don't append any Message-ID to the mail, let the SMTP do the job, else use the string to generate a unique ID using email.utils.make_msgid(). The generated value is returned as last argument. For example use the name of your application.
  • date (int or None) - utc time in second from the epoch or None. If None then use curent time time.time() instead.
  • headers (list of tuple) - a list of (field, value) tuples to fill in the mail header fields. Values are encoded using default_charset.
Returns: tuple
(payload, mail_from, rcpt_to, msg_id)
  • payload (str) is the content of the email, generated from the message
  • mail_from (str) is the address of the sender to pass to the SMTP host
  • rcpt_to (list) is a list of the recipients addresses to pass to the SMTP host of the form [ 'a@b.com', c@d.com', ]. This combine all recipients, carbone copy addresses and blind carbone copy addresses.
  • msg_id (None or str) None if message_id_string==None else the generated value for the message-id. If not None, this Message-ID is already written into the payload.
>>> import email.mime.text
>>> msg=email.mime.text.MIMEText('The text.', 'plain', 'us-ascii')
>>> # I could use build_mail() instead
>>> payload, mail_from, rcpt_to, msg_id=complete_mail(msg, ('Me', 'me@foo.com'),
... [ ('Him', 'him@bar.com'), ], 'Non unicode subject', 'iso-8859-1',
... cc=['her@bar.com',], date=1313558269, headers=[('User-Agent', u'pyzmail'), ])
>>> print payload
... # 3.X encode  User-Agent: using 'iso-8859-1' even if it contains only us-asccii
... # doctest: +ELLIPSIS  
Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
From: Me <me@foo.com>
To: Him <him@bar.com>
Cc: her@bar.com
Subject: =?iso-8859-1?q?Non_unicode_subject?=
Date: ...
User-Agent: ...pyzmail...
<BLANKLINE>
The text.
>>> print 'mail_from=%r rcpt_to=%r' % (mail_from, rcpt_to)
mail_from='me@foo.com' rcpt_to=['him@bar.com', 'her@bar.com']

compose_mail(sender, recipients, subject, default_charset, text, html=None, attachments=[], embeddeds=[], cc=[], bcc=[], message_id_string=None, date=None, headers=[])

source code 

Compose an email regarding the arguments. Call build_mail() and complete_mail() at once.

Read the parameters descriptions of both functions build_mail() and complete_mail().

Returned value is the same as for build_mail() and complete_mail(). You can pass the returned values to send_mail() or send_mail2().

Returns: tuple
(payload, mail_from, rcpt_to, msg_id)
>>> payload, mail_from, rcpt_to, msg_id=compose_mail((u'Me', 'me@foo.com'), [(u'Him', 'him@bar.com')], u'the subject', 'iso-8859-1', ('Hello world', 'us-ascii'), attachments=[('attached', 'text', 'plain', 'text.txt', 'us-ascii')])

send_mail2(payload, mail_from, rcpt_to, smtp_host, smtp_port=25, smtp_mode='normal', smtp_login=None, smtp_password=None)

source code 

Send the message to a SMTP host. Look at the send_mail() documentation. send_mail() call this function and catch all exceptions to convert them into a user friendly error message. The returned value is always a dictionary. It can be empty if all recipients have been accepted.

Returns: dict
This function return the value returnd by smtplib.SMTP.sendmail() or raise the same exceptions.

This method will return normally if the mail is accepted for at least one recipient. Otherwise it will raise an exception. That is, if this method does not raise an exception, then someone should get your mail. If this method does not raise an exception, it returns a dictionary, with one entry for each recipient that was refused. Each entry contains a tuple of the SMTP error code and the accompanying error message sent by the server.

Raises:
  • smtplib.SMTPException - Look at the standard smtplib.SMTP.sendmail() documentation.

send_mail(payload, mail_from, rcpt_to, smtp_host, smtp_port=25, smtp_mode='normal', smtp_login=None, smtp_password=None)

source code 

Send the message to a SMTP host. Handle SSL, TLS and authentication. payload, mail_from and rcpt_to can come from values returned by complete_mail(). This function call send_mail2() but catch all exceptions and return friendly error message instead.

Parameters:
  • payload (str) - the mail content.
  • mail_from (str) - the sender address, for example: 'me@domain.com'.
  • rcpt_to (list) - The list of the recipient addresses in the form [ 'a@b.com', c@d.com', ]. No names here, only email addresses.
  • smtp_host (str) - the IP address or the name of the SMTP host.
  • smtp_port (int) - the port to connect to on the SMTP host. Default is 25.
  • smtp_mode (str) - the way to connect to the SMTP host, can be: 'normal', 'ssl' or 'tls'. default is 'normal'
  • smtp_login (str or None) - If authentication is required, this is the login. Be carefull to UTF8 encode your login if it contains non us-ascii characters.
  • smtp_password (str or None) - If authentication is required, this is the password. Be carefull to UTF8 encode your password if it contains non us-ascii characters.
Returns: dict or str
This function return a dictionary of failed recipients or a string with an error message.

If all recipients have been accepted the dictionary is empty. If the returned value is a string, none of the recipients will get the message.

The dictionary is exactly of the same sort as smtplib.SMTP.sendmail() returns with one entry for each recipient that was refused. Each entry contains a tuple of the SMTP error code and the accompanying error message sent by the server.

Example:

>>> send_mail('Subject: hello\n\nmessage', 'a@foo.com', [ 'b@bar.com', ], 'localhost') #doctest: +SKIP
{}

Here is how to use the returned value:

   if isinstance(ret, dict):
     if ret:
       print 'failed' recipients:
       for recipient, (code, msg) in ret.iteritems():
           print 'code=%d recipient=%s     error=%s' % (code, recipient, msg)
     else:
       print 'success'
   else:
     print 'Error:', ret

To use your GMail account to send your mail:

   smtp_host='smtp.gmail.com'
   smtp_port=587
   smtp_mode='tls'
   smtp_login='your.gmail.addresse@gmail.com'
   smtp_password='your.gmail.password'

Use your GMail address for the sender !