0

I wrote a little Python program in which I send e-mails to recepients from .csv file.

import csv
import smtplib

f = open('output.csv')
csv_f = csv.reader(f)
email=[]
for row in csv_f:
    if row:
        email.append(row[2])

fromaddr = MY MAIL
toaddrs  = email
subject = 'Čestitamo!'
text = 'ččšpšžćčđšđ'
msg = 'Subject: %s\n\n%s' % (subject, text)


username = MY_USER
password = MY_PASS


try:
    server = smtplib.SMTP('smtp.gmail.com:587')

    server.starttls()
    server.login(username,password)
    server.sendmail(fromaddr, email, msg)
    server.quit()
    print('Mail sent!')
except Exception as e:
    print("ERROR!")
    print(e)

Program like this gives error: 'ascii' codec can't encode character '\u010c' in position 9: ordinal not in range

Tried to encode as utf-8, the mail is sent, but i get this:

Äestitamo! ÄÄÅ¡pšžćÄÄ‘Å¡Ä‘

Then i tried to decode that on many ways, but i couldn't get proper Croatian letters č,ć,ž,š,đ.

What should I do so i can have proper croatian letters on send mail?

EDIT

changed a line to:

server.sendmail(fromaddr, email, msg.encode("windows-1250"))

now i have š and ž correct!

for č i've got è, for ć i've got æ, for đ i've got ð

omicito
  • 59
  • 8

1 Answers1

2

You will have to use the mime module to send messages containing non plain ascii characters. If you are fine with a base64 encoding of the message, you can simply use an email.mime.text.MIMEText:

msg = email.mime.text.MIMEText('nččšpšžćčđšđ',_charset='utf8')
msg.add_header('Subject', 'Čestitamo!')
server.send_message(msg, fromaddr, email)

If you do not like base64 encoding for the message body, you will have to use an email.mime.MIMENonMultipart and explicitely set the headers and encode the body:

msg = email.mime.nonmultipart.MIMENonMultipart('text', 'plain')
msg.add_header('Content-Transfer-Encoding', '8bits')
msg.add_header('Charset', 'utf8')
msg.add_header('Subject', 'Čestitamo!')
msg.set_payload('ččšpšžćčđšđ'.encode('utf8'))
server.send_message(msg, fromaddr, email)

Note: I have used utf8 encoding here, but this method can use any other encoding able to represent Croatian characters...

Serge Ballesta
  • 121,548
  • 10
  • 94
  • 199