Digital Marketing

Python email by smtplib and MIMEMultipart example

"""The first step is to create an SMTP object, each object is used for connection
with one server."""

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
server = smtplib.SMTP('smtp.i88.ca', 587)
#debug
server.set_debuglevel(1)
# or server.set_debuglevel(True) # show communication with the server
#TLS
server.starttls()
#Next, log in to the server
server.login("user-name", "password")
me="sender@i88.ca"
you="recipient@i88.ca"
#Send the mail
msg = MIMEMultipart('alternative')
msg['Subject'] = "Test example"
msg['From'] = me
msg['To'] = you

html = '<html><body><p>Hi, I have the following contents for you!</p></body></html>'
part2 = MIMEText(html, 'html')
# or part2=MIMEText(text, 'plain')
msg.attach(part2)

server.sendmail(me, you, msg.as_string())
server.quit()


The function returns a dict of any addresses it could not forward to; other connection problems raise errors.
Tested on Windows, it should work on all POSIX platforms.
import smtplib
 
def sendemail(from_addr, to_addr_list, cc_addr_list,
subject, message,
login, password,
smtpserver='smtp.gmail.com:587'):
header = 'From: %s\n' % from_addr
header += 'To: %s\n' % ','.join(to_addr_list)
header += 'Cc: %s\n' % ','.join(cc_addr_list)
header += 'Subject: %s\n\n' % subject
message = header + message
 
server = smtplib.SMTP(smtpserver)
server.starttls()
server.login(login,password)
problems = server.sendmail(from_addr, to_addr_list, message)
server.quit()
return problems
Example use:
sendemail(from_addr    = 'python@RC.net', 
to_addr_list = ['RC@gmail.com'],
cc_addr_list = ['RC@xx.co.uk'],
subject = 'Howdy',
message = 'Howdy from a python function',
login = 'pythonuser',
password = 'XXXXX')

Comments

Popular posts from this blog

Make online money from the Internet