473,699 Members | 2,266 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

email modules and attachments that aren't there

Hello all,

I have written a short function, based on a recipe in the Python
Cookbook, that sends an e-mail. The function takes arguments that
define who the e-mail is to, from, the subject, the body and an optional
list of attachments.

The function works also perfectly, bar one slight problem. If you
attempt to send an e-mail with just a body and no attachments, the
receiving client still thinks that there is an attachment (so far tested
in Mozilla Thunderbird and the Yahoo! webmail client). Although this
clearly isn't a major problem, it is irritating and I am hoping to use
my code at work. Obviously I can't be sending out badly formed e-mails
to my clients.

I can't for the life of me work out why. I have compared my code to
every example that I can find in the Python documentation, on the
archives of this newsgroup and of the Python Tutor list, and one or two
random searches but can't see what is happening. Any advice or
suggestions would be welcome.

Thank you for your help,

Russell Bungay
--
The Duck Quacks:
http://www-users.york.ac.uk/~rb502/ - Homepage
http://www-users.york.ac.uk/~rb502/blog/quack.shtml - Blog
http://www.flickr.com/photos/lsnduck/ - Photos

Code:

def sendEmail(msg_t o, msg_from, msg_subject, message, attachments=[]):

main_msg = email.Message.M essage()
main_msg['To'] = ', '.join(msg_to)
main_msg['From'] = msg_from
main_msg['Subject'] = msg_subject
main_msg['Date'] = email.Utils.for matdate(localti me=1)
main_msg['Message-ID'] = email.Utils.mak e_msgid()
main_msg['Mime-version'] = '1.0'
main_msg['Content-type'] = 'Multipart/mixed'
main_msg.preamb le = 'Mime message\n'
main_msg.epilog ue = ''

body_encoded = quopri.encodest ring(message, 1)
body_msg = email.Message.M essage()
body_msg.add_he ader('Content-type', 'text/plain')
body_msg.add_he ader('Content-transfer-encoding', 'quoted-printable')
body_msg.set_pa yload(body_enco ded)
main_msg.attach (body_msg)

for attachment in attachments:

content_type, ignored = mimetypes.guess _type(attachmen t)
if content_type == None:
content_type = 'application/octet-stream'
contents_encode d = cStingIO.String IO()
attach_file = open(attachment , 'rb')
main_type = content_type[:content_type.f ind('/')]
if main_type == 'text':
cte = 'quoted-printable'
quopri.encode(a ttach_file, contents_encode d, 1)
else:
cte = 'base64'
base64.encode(a ttach_file, contents_encode d)
attach_file.clo se()

sub_msg = email.Message.M essage()
sub_msg.add_hea der('Content-type', content_type, name=attachment )
sub_msg.add_hea der('Content-transfer-encoding', cte)
sub_msg.set_pay load(contents_e ncoded.getvalue ())
main_msg.attach (sub_msg)

smtp = smtplib.SMTP(se rver)
smtpfail = smtp.sendmail(m sg_from, ', '.join(msg_to),
main_msg.as_str ing())
smtp.quit()
Jan 9 '06 #1
4 1937
Russell Bungay wrote:
Hello all,

I have written a short function, based on a recipe in the Python
Cookbook, that sends an e-mail. The function takes arguments that
define who the e-mail is to, from, the subject, the body and an optional
list of attachments.

The function works also perfectly, bar one slight problem. If you
attempt to send an e-mail with just a body and no attachments, the
receiving client still thinks that there is an attachment (so far tested
in Mozilla Thunderbird and the Yahoo! webmail client).
<snip>
Code:

def sendEmail(msg_t o, msg_from, msg_subject, message, attachments=[]):

main_msg = email.Message.M essage()
main_msg['To'] = ', '.join(msg_to)
main_msg['From'] = msg_from
main_msg['Subject'] = msg_subject
main_msg['Date'] = email.Utils.for matdate(localti me=1)
main_msg['Message-ID'] = email.Utils.mak e_msgid()
main_msg['Mime-version'] = '1.0'
main_msg['Content-type'] = 'Multipart/mixed'
main_msg.preamb le = 'Mime message\n'
main_msg.epilog ue = ''


Would it be the 'Content-Type' header? I've no expertise in this, but
doesn't 'multipart' mean 'has attachments'?

Gerard

Jan 9 '06 #2
Hello,
main_msg['Content-type'] = 'Multipart/mixed'

Would it be the 'Content-Type' header? I've no expertise in this, but
doesn't 'multipart' mean 'has attachments'?


Brilliant, thank you. A swift test on the number of attachments and
changing the header suitably does the job.

Thank you for your help,

Russell
--
The Duck Quacks:
http://www-users.york.ac.uk/~rb502/ - Homepage
http://www-users.york.ac.uk/~rb502/blog/quack.shtml - Blog
http://www.flickr.com/photos/lsnduck/ - Photos
Jan 10 '06 #3
Hello,
main_msg['Content-type'] = 'Multipart/mixed'

Would it be the 'Content-Type' header? I've no expertise in this, but
doesn't 'multipart' mean 'has attachments'?

Brilliant, thank you. A swift test on the number of attachments and
changing the header suitably does the job.


That isn't quite all there is to it, the e-mail construction needs a
slight change as well. Roughly working code below.

Ta,

Russell

Code:

def sendEmail(msg_t o, msg_from, msg_subject, message, attachments=[]):

main_msg = email.Message.M essage()
main_msg['To'] = ', '.join(msg_to)
main_msg['From'] = msg_from
main_msg['Subject'] = msg_subject
main_msg['Date'] = email.Utils.for matdate(localti me=1)
main_msg['Message-ID'] = email.Utils.mak e_msgid()
main_msg['Mime-version'] = '1.0'
main_msg.preamb le = 'Mime message\n'
main_msg.epilog ue = ''

body_encoded = quopri.encodest ring(message, 1)

if len(attachments ) <> 0:
main_msg['Content-type'] = 'Multipart/mixed'
body_msg = email.Message.M essage()
body_msg.add_he ader('Content-type', 'text/plain')
body_msg.add_he ader('Content-transfer-encoding',
'quoted-printable')
body_msg.set_pa yload(body_enco ded)
main_msg.attach (body_msg)
for attachment in attachments:
content_type, ignored = mimetypes.guess _type(attachmen t)
if content_type == None:
content_type = 'application/octet-stream'
contents_encode d = cStringIO.Strin gIO()
attach_file = open(attachment , 'rb')
main_type = content_type[:content_type.f ind('/')]
if main_type == 'text':
cte = 'quoted-printable'
quopri.encode(a ttach_file, contents_encode d, 1)
else:
cte = 'base64'
base64.encode(a ttach_file, contents_encode d)
attach_file.clo se()

sub_msg = email.Message.M essage()
sub_msg.add_hea der('Content-type', content_type, name=attachment )
sub_msg.add_hea der('Content-transfer-encoding', cte)
sub_msg.set_pay load(contents_e ncoded.getvalue ())
main_msg.attach (sub_msg)

else:
main_msg['Content-type'] = 'text/plain'
main_msg['Content-transfer-encoding'] = 'quoted-printable'
main_msg.set_pa yload(body_enco ded)

smtp = smtplib.SMTP('s erver')
smtpfail = smtp.sendmail(m sg_from, ', '.join(msg_to),
main_msg.as_str ing())
smtp.quit()
Jan 10 '06 #4
Russell Bungay wrote:
for attachment in attachments:
<snip contents of for loop> sub_msg = email.Message.M essage()
sub_msg.add_hea der('Content-type', content_type, name=attachment )
sub_msg.add_hea der('Content-transfer-encoding', cte)
sub_msg.set_pay load(contents_e ncoded.getvalue ())
main_msg.attach (sub_msg)


These lines should of course be within the for, not outside it. Apologies.

Russell
Jan 10 '06 #5

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

Similar topics

4
3730
by: Paul Schmidt | last post by:
Dear list: I am new to python, and I am trying to figure out the short answer on something. I want to open a POP3 mailbox, read the enclosed mail using the POP3 module, , and then process it using the email module. Environment Python 2.3.4, Mandrake Linux 9.0 patched up the wazoo...
3
3142
by: LutherRevisited | last post by:
Is there a way I can put a message together without having to download any attachments there may be at the same time. I'm not having any problems dealing with attachments, but the way I'm doing things makes me download the complete message first, attachements and all: mail = for j in M.retr(i): mail.append(j.rstrip()) inMail = email.message_from_string('\r\n'.join(mail)) I don't have a real problem per se with this, it's just that I...
2
6723
by: brettk | last post by:
Hello All, Here's what I'm trying to do: I need to connect to a pop3 server, download all messages, and copy all of the attachments into a specific directory. The actual email message is unimportant. Now, I've found plenty of examples that strip the attachments from an email message, but most (if not all) of them take a file parameter. My question is this:
0
1749
by: YYZ | last post by:
Problem: I need to allow my users to drag an email out of Outlook and drop it on a winform -- from there, I need to get the text of that email (not just the sender and subject) -- from there I'll save it myself in a database. This is to allow them to track all the correspondance that happens between themselves and a customer. I've found code examples of how to do this with an ATTACHMENT out of Outlook, but not the email message itself...
10
4964
by: OdAwG | last post by:
Hello All, Is it possible to send an email from Access? I found a Microsoft article on how to do this but I keep getting an error "RUNTIME ERROR 438" -- Object doesn't support this property or method. Listed below is the article from microsoft How to use a recordset to send Outlook e-mail to multiple recipients in Microsoft Access http://support.microsoft.com/?id=318881
1
2130
by: darklink64 | last post by:
Hi, I've recently set up a database, but have not experience of VBA and need to find a way of solving this problem. Basically, I would like to make a form with two buttons. On clicking one button an input box should appear asking for an email address and then an email should be sent to that address with an attachement. The other button should send an email to all the addresses in the email address field in a table.
2
2646
by: oyster | last post by:
I find that the existing email moudle is some hard for me to understand, especially the part of how to set the CC, BCC and attach the files. Is there any more easy one like this p-code? import easyemail smtpserver=easyemail.server('something') smtpserver.login('usr@gmail.com', pwd) newletter=smtpsever.letter(smtpserver) newletter.sendto= newletter.sendcc=
2
2031
by: David Veeneman | last post by:
My web app creates several temporary files, then attaches them to an email that it sends out. When the app attches the documents to the email, .NET locks the files. My problem is that they aren't getting unlocked. When the app runns, the first thing it does is delete the files left from its last run. So, on the second run of the app, I'm getting this error message: " The process cannot access the file 'D:\ ... \MyFile.txt' because it is...
3
1449
by: =?Utf-8?B?TWlrZQ==?= | last post by:
Hi, I'm using the bellow code to send emails in a Website that I uploaded in one of my client's server where it has SMTP installed, BUT some users are receiving email some others aren't !!?So, what could be the problem? knowing that all users are using the same code and hitting the same server. MailMessage objMailMsg = new MailMessage(strFrom,
0
8689
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9035
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8885
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7752
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6534
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5875
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4376
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3058
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2348
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.