Wednesday, June 4, 2008

Sending email (smtp) using python

bash$ python
Python 2.1.1 (#1, Dec 29 2004, 11:06:29)
[GCC 3.3.3] on linux2
Type "copyright", "credits" or "license" for more information.
>>>
>>> # First we need to import smtplib, which we use for sending email
>>>
>>> import smtplib
>>>
>>> # Next we compose the message we want to be sent, in MIME format.
>>> # You can go ahead and include attachments or whatever.
>>> # One quick way would be to use MS Outlook or something to compose
>>> # the message, then save it as .eml, and copy the source.
>>> # Note here that "From:", "To:", "Cc:" etc are what your recipients
>>> # will see in the header, but does not reflect on who the message is
>>> # actually from, or is actually sent to.
>>> # The message only goes to people who you specify in the sendmail() call.
>>> # Note also that the \r\n pattern should separate each field in the header
>>> # and the \r\n\r\n separates header from the body.
>>>
>>> message = """From: John Dove <john@dove.com>\r\nTo: John Dove <john@dove.com>\r\nCc: Jane Dove <jane@dove.com>\r\nSubject: Hi!\r\n\r\n
... Hi John,

...
... How are you doing man?
... Just mailing in to let you know that I exist..
... Just woke up when you were loitering around in the pantry :D
...
... /your alter-ego(2)
... """
>>>
>>> # Now we initiate the smtp connection
>>>
>>> mailServer = smtplib.SMTP("smtp.server.com")
>>>
>>> # Now we actually send the email..
>>> mailServer.sendmail("sender@somewhere.com", ["recipient1@somewhere.com",
... "recipient2@somewhere.com", "john.dove@somewhereelse.com"], message);

{}
>>> # Now that we are done, we 'hang up' the connection
>>>
>>> mailServer.close()
>>>
>>> # bbye :D
>>>

Reference:
http://www.eskimo.com/~jet/python/examples/mail/smtp1.html

.

No comments: