Pelicanux

Just A Few Random Words

Sending Mails With Python

Ok, it has been quite a while since I wrote my last article, so let’s move my fat lazy ass and gather some ideas. I remember having a hard time writting a dummy email-sending script in python; Once again because of encoding issues. Here is a script to simply perform this task, with an account requiring authentication:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#
## Players
#
mail_receiver = [
  'my@mondomain.net',
  'you@mondomain.net',
  'him@mondomain.net',
]

#
## Rough email content (subject, body, Cc, To, ...)
mail_sender = 'some@somedomain.net'
mail_to = ['lui@mondomain.net',]
mail_cc = ['toi@mondomain.net',]
mail_text = "Bonjour,\n\n"
mail_text+= "Blah blah blah je suis Français et mon alphabet fait chier.\n"
mail_text+= "é - à ÀÇù\n\n"
mail_server = 'localhost'

pretty_mail_file = os.path.basename(mail_file)
print("Sending file "+mail_file+" by email")
msg = MIMEMultipart()
msg['From'] = mail_sender
msg['To'] = COMMASPACE.join(mail_to)
msg['cc'] = COMMASPACE.join(mail_cc)
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = "En Français avec des caractères spéciaux"

#
## This lets me being French. Well, not sure for the subject
#
msg.attach( MIMEText(mail_text, _charset='utf-8') )

#
## If I want to attach some files
#
part = MIMEBase('application', 'octet-stream')
part.set_payload(open(mail_file, "rb").read())
part.add_header('Content-Disposition', 'attachment; filename="%s"' % pretty_mail_file)
Encoders.encode_base64(part)
msg.attach(part)

#
## OK mail created, let's send it
#
try:
  smtp = smtplib.SMTP(mail_server)
  try:
      smtp.login(login, password) # Here is how to login if server requests authentication
  Except SMTPAuthenticationError,e:
      print 'Authentication refused, error given: '+str(e)+'\n'
  smtp.sendmail(mail_sender, mail_receiver, msg.as_string())
  smtp.close()
  print("Mail successfully sent")
except Exception, e:
  print("Trouble encounted sending mail", "ERROR")

Hope this article will be of some help.