473,395 Members | 1,348 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Sending email in utf-8?

Hi,

I have an email that's in the utf-8 encoding, and I'm getting this
error message when I try to send it using smtplib:

* Module smtplib, line 688, in sendmail
* Module smtplib, line 485, in data
* Module smtplib, line 312, in send
* Module socket, line 1, in sendall

UnicodeEncodeError: 'ascii' codec can't encode characters in position
263-264: ordinal not in range(128)

any suggestions on how I can approach this so that the email can be
sent without raising errors?

Nov 7 '05 #1
5 12582
"morphex" <mo*****@gmail.com> wrote:
I have an email that's in the utf-8 encoding, and I'm getting this
error message when I try to send it using smtplib:

* Module smtplib, line 688, in sendmail
* Module smtplib, line 485, in data
* Module smtplib, line 312, in send
* Module socket, line 1, in sendall

UnicodeEncodeError: 'ascii' codec can't encode characters in position
263-264: ordinal not in range(128)

any suggestions on how I can approach this so that the email can be
sent without raising errors?


looks like you're confusing Unicode (character set) and UTF-8 (encoding).

smtplib only deals with 8-bit character streams; if you want to use a specific
encoding, you have to apply it yourself *before* you call the library:

HOST = "..."
FROM = "..."
TO = "..."
BODY = u"..."

server = smtplib.SMTP(HOST)
server.sendmail(FROM, [TO], BODY.encode("utf-8"))
server.quit()

</F>

Nov 7 '05 #2
That works, kinda. I get strange characters now like this

"""
Date: Mon, 7 Nov 2005 11:38:29 -0700 (MST)
Message-Id: <20*************************@thinkering.com>
To: mo****@nidelven-it.no, mo****@nidelven-it.no
From: mo****@nidelven-it.no
Subject: Order confirmation
Content-Type: text/plain; charset="utf-8"
X-Bogosity: No, tests=bogofilter, spamicity=0.000000, version=0.92.8

Thank you for your order, it is copied here for your convenience, and
we will process it shortly.

Name: ø
Phone: ø
Email: mo****@nidelven-it.no
Comments: asdf
"""

but at least it doesn't raise any errors.

Nov 7 '05 #3
morphex wrote:
That works, kinda. I get strange characters now like this

"""
Date: Mon, 7 Nov 2005 11:38:29 -0700 (MST)
Message-Id: <20*************************@thinkering.com>
To: mo****@nidelven-it.no, mo****@nidelven-it.no
From: mo****@nidelven-it.no
Subject: Order confirmation
Content-Type: text/plain; charset="utf-8"
X-Bogosity: No, tests=bogofilter, spamicity=0.000000, version=0.92.8

Thank you for your order, it is copied here for your convenience, and
we will process it shortly.

Name: ø
Phone: ø
Email: mo****@nidelven-it.no
Comments: asdf
"""

but at least it doesn't raise any errors.


This is a method I have clipped from one of my projects. It should
pretty much cover everything you would want to do while sending mails.
def Workgroup_mailFormAction(self, to=None, cc=None, bcc=None,
inReplyTo=None,
subject=None, body='',
attachments=None, mfrom=None,
REQUEST=None):
"""
Sends a message. Many of the input parameters are not currently
used,
but can be used for skinning the functionlity.
"""
site_encoding = self._site_encoding()
##################
# Create the message
msg = Message()
msg.set_payload(body, site_encoding)
#####################################
# if attachment, convert to multipart
# file fields are posted even if empty, so we need to remove
those :-s
if attachments is None:
attachments = []
attachments = [a for a in attachments if a]
if attachments:
mimeMsg = MIMEMultipart()
mimeMsg.attach(msg)
for attachment in attachments:
# Add the attachment
tmp = email.message_from_string(str(attachment.headers))
filename = tmp.get_param('filename', 'Attachment',
'Content-Disposition')
# clean up IE paths
filename = filename[max(filename.rfind('/'),
filename.rfind('\\'),
filename.rfind(':')
)+1:]
contentType = tmp['Content-Type']
attach_part = Message()
attach_part.add_header('Content-Type', contentType,
name=filename)
attach_part.add_header('Content-Disposition',
'attachment', filename=filename)
attach_part.set_payload(attachment.read())
Encoders.encode_base64(attach_part)
mimeMsg.attach(attach_part)
msg = mimeMsg
########################
# set headers on message
####
if to is None:
to = []
if mfrom:
to.append(mfrom)
msg['From'] = mfrom
msg['Reply-To'] = mfrom
to = ','.join(to)
if to: msg['To'] = to
####
if cc is None:
cc = []
cc = ','.join(cc)
if cc: msg['Cc'] = cc
####
if bcc is None:
bcc = []
bcc = ','.join(bcc)
if bcc: msg['Bcc'] = bcc
####
msg['Date'] = self.ZopeTime().rfc822() # needed by some servers
if inReplyTo:
msg['In-Reply-To'] = inReplyTo
msg['Subject'] = Header(subject, site_encoding)
##################
# Send the message
SMTPserver = self._mailhost()
success = 0
try:
cleaner = lambda adresses: [adress.strip() for adress in
adresses.split(',') if adress.strip()]
all_receivers = cleaner(to) + cleaner(cc) + cleaner(bcc)
all_receivers = list(set(all_receivers))
if all_receivers: # only send if any recipients
self._mailhost().send(str(msg), mto=all_receivers,
mfrom=mfrom)
success = 1
except:
pass
--

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science
Nov 8 '05 #4
"morphex" <mo*****@gmail.com> wrote:
"""
Date: Mon, 7 Nov 2005 11:38:29 -0700 (MST)
Message-Id: <20*************************@thinkering.com>
To: mo****@nidelven-it.no, mo****@nidelven-it.no
From: mo****@nidelven-it.no
Subject: Order confirmation
Content-Type: text/plain; charset="utf-8"
X-Bogosity: No, tests=bogofilter, spamicity=0.000000, version=0.92.8

Thank you for your order, it is copied here for your convenience, and
we will process it shortly.

Name: ø
Phone: ø
Email: mo****@nidelven-it.no
Comments: asdf
"""


that's 0xC3 0xB8 (at least according to my mail reader), which, translated
back from UTF-8, looks like a typically norsk character to me...
name = "\xc3\xb8".decode("utf-8") print name ø
import unicodedata
unicodedata.name(name)

'LATIN SMALL LETTER O WITH STROKE'

try adding a "Mime-Version: 1.0" header to your mail.

a "Content-Transfer-Encoding: 8bit" might not hurt either (or run the body through
quopri.encodestring() after you've encoded it, and use "Content-Transfer-Encoding:
quoted-printable").

(also check the email package: http://docs.python.org/lib/module-email.html )

</F>

Nov 8 '05 #5
By turning everything into unicode objects (unicode(string)) and then
running body.encode('utf-8') and using quoted printable, it works.

Thanks for all the help, it's really appreciated!

Nov 10 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

13
by: joe215 | last post by:
I want my users to send emails from a Windows app that I am developing in Visual Basic.NET 2003. I found a good example of sending email to a SMTP server using the SmtpMail class. However, using...
2
by: Mr. x | last post by:
Hello, I am sending emails with Hebrew contents. When receiving emails - I cannot see the Hebrew characters (it is not outlook express configuration, because when receiving emails from friends -...
3
by: Sydney | last post by:
Hi, I am trying to construct a WSE 2.0 security SOAP request in VBScript on an HTML page to send off to a webservice. I think I've almost got it but I'm having an issue generating the nonce...
7
by: kingski | last post by:
Any idea about this ? http://www.developerfusion.co.uk/forums/thread/114379/#114379 "Can any one help me as i am building a shopping cart and it supports multiple currencies but while sending...
4
by: Roger Withnell | last post by:
I'm sending Russian text in an email generated from the website which displays in the email as ?????????? The website is set to codepage 65001 and the charset to utf-8. Please advise. ...
1
by: Grzegorz ¦lusarek | last post by:
Hi all. I sending email using standard python modules smtplib, email, coding email in utf but subject of message is not coded properly. In subject i use my national characters (polish) and after...
3
by: virtualweb | last post by:
Hello: I need to send a bit of HTML and Javascrpt on the body of an email from my perl script in order to have the recipient get a link that will openup a new window with a PopUp. For some...
9
by: neovantage | last post by:
hey geeks, I have a small mail script which will cause a PHP script to send a receipt upon clicking the submit button, by an HTML mail. This mail contains special characters, namely 'å', 'ä' and...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.