473,322 Members | 1,610 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,322 software developers and data experts.

Sample code to build rfc822 mail message building

Dear All,

I am new to python world. I have pasted my code
which I used it to build rfc822 format mails for
webbased mailing system task(which is like
to yahoo.com web interface). Now I am asking some
suggestions and guidence regarding this below code.
Still What way I can improve this code. If anyone find
error kindly let me know how to correct it.

# This function to handle attachment files
def addAttachment(filename,ctype):
#mimetypes guesses the type of file and stores it
in ctype
maintype, subtype = ctype.split('/', 1)
if not os.path.exists(filename): return 0
fp = open(filename, 'rb') #open the file
if maintype == 'text':
#check for maintype value and encode and
return according to the
# type of file
attach = MIMEText(fp.read(),_subtype=subtype)
elif maintype == 'message' and subtype ==
"rfc822":
attach = email.message_from_file(fp)
attach = MIMEMessage(attach)
elif maintype == 'message' and subtype <>
"rfc822":
attach = email.message_from_file(fp)
elif maintype == 'image':
attach = MIMEImage(fp.read(),_subtype=subtype)
elif maintype == 'audio':
attach = MIMEAudio(fp.read(),_subtype=subtype)
else:
#print maintype, subtype #if it does not
equal any of the
#above we print to screen and encode and
return
attach = MIMEBase(maintype, subtype) #the
encoded value
attach.set_payload(fp.read())
encode_base64(attach)

fp.close()
filename = os.path.basename(filename)
attach.add_header('Content-Disposition',
'attachment',filename=filename)
return attach

#This function base I try to build email message
def create_mail(domain, user, form, from_name):
to = cc = bcc = subject = body = ''
attachments = []
send_addresses = ''
if form.has_key('to'):
to = form['to'].value.strip()
send_addresses = to
if form.has_key('cc'):
cc = form['cc'].value.strip()
send_addresses = to + ',' + cc
if form.has_key('bcc'):
bcc = form['bcc'].value.strip()
send_addresses = to + ',' + cc + ',' + bcc
if form.has_key('subject'): subject =
form['subject'].value
if form.has_key('body'): body = form['body'].value
if form.has_key('attachments[]'): attachments =
form.getlist("attachments[]")

if not len(attachments) > 0:
# This header is for non Multipart message
# I want to know reduce below redundant code
msg = MIMEBase('text','html')
msg['Return-Path'] = user+'@'+domain
msg['Date'] = formatdate(localtime=1)
msg['Subject'] = subject
msg['From'] = from_name
msg['To'] = to
msg["Cc"] = cc
msg.set_payload(body)
# Guarantees the message ends in a newline
msg.epilogue = ''
else:
msg = MIMEMultipart()
msg['Return-Path'] = user+'@'+domain
msg['Date'] = formatdate(localtime=1)
msg['Subject'] = subject
msg['From'] = from_name
msg['To'] = to
msg["Cc"] = cc
body = MIMEText(body) #Here is the bod
msg.attach(body)
# Guarantees the message ends in a newline
msg.epilogue = ''
for eachfile in attachments:
row = eachfile.split(':')
att_name = row[0]
att_type = row[1]
filename = domaindir + '/' + domain + '/'
+ user + '/temp/upload/' + att_name
if addAttachment(filename,att_type):
attach =
addAttachment(filename,att_type)
msg.attach(attach)

# To send message to all the send_addresses
for eachid in send_addresses.split(","):
fh = os.popen('/bin/sendmail %s'%
(eachid),'w')
fh.write(msg.as_string())
fh.close()



__________________________________________________ ________
Free antispam, antivirus and 1GB to save all your messages
Only in Yahoo! Mail: http://in.mail.yahoo.com
Aug 6 '05 #1
1 2379
On Sat, 6 Aug 2005 08:45:30 +0100 (BST), praba kar <pr*********@yahoo.co.in> wrote:
Dear All,

I am new to python world. I have pasted my code
which I used it to build rfc822 format mails for .... Still What way I can improve this code. If anyone find
error kindly let me know how to correct it. .... #This function base I try to build email message
def create_mail(domain, user, form, from_name):
to = cc = bcc = subject = body = ''
attachments = []


Document methods with proper grammar, as doc strings, and use more direct
wording:

def create_mail(domain, user, form, from_name):
"""Build and return an RFC 2822 message with (something about
what the parameters do) and an empty body. (More details.)
"""
to = cc = bcc = subject = body = ''
attachments = []

If you feed your code to the 'pydoc' utility, the output should be readable.

Somewhere you also might need to describe what subset of RFC 2822 and MIME
you implement, or what your "mail metaphor" is. Different people think
differently about mails. I, for example, don't know what you mean by
"attachment" -- the MIME RFCs use much richer concepts.

/Jorgen

--
// Jorgen Grahn <jgrahn@ Ph'nglui mglw'nafh Cthulhu
\X/ algonet.se> R'lyeh wgah'nagl fhtagn!
Aug 7 '05 #2

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

Similar topics

0
by: Dafella | last post by:
The following is code from Xeoport. It is suppose to access my pop3 account and load email into Mysql database. It's not inserting and there is no log or anything to tell me why. Here is the...
0
by: Chris McKeever | last post by:
I am trying to modify the Mailman Python code to stop mapping MIME-types and use the extension of the attachment instead. I am pretty much clueless as to what I need to do here, but I think I have...
0
by: Michael B Allen | last post by:
How can I zoom in on what's going on below? $ archivemail -n ~/Maildir/.Lists.* /home/miallen/Maildir/.Lists.CIFS: I would have archived 11 of 29 message(s) in 0.1 seconds...
1
by: John Doe | last post by:
I've never used a factory and would like to get some help. The class mailbox.UnixMailbox has a defination for a factory. __init__(self, fp, factory=<class rfc822.Message>) where fp is a file...
1
by: Malcolm Dew-Jones | last post by:
I am looking for an xml grammar for mail messages. It needs to be able to identify the structure of a mime message and also the structure of a non-mime (but rfc822) message. I can invent one...
4
by: Nemesis | last post by:
Hi all, I found that the function parsedate_tz of the rfc822 module has a bug (or at least I think so). I found a usenet article (message-id: <2714d.q75200@myg.winews.net>) that has this Date...
7
by: dm_dal | last post by:
I have a solution in VS.Net 2003. It contains 1 - asp.net project(c#), 1 - c# class library project and 1 - db project. When I try to build the solution, I get the following error: Could not...
4
by: Henry | last post by:
Does anybody have a real-world sample of buiding a treeview control using data from database tables? All the sample code I have found either builds the treeview manually or uses a file directory...
0
by: M.-A. Lemburg | last post by:
On 2008-10-25 08:39, Akira Kitada wrote: Please post a bug report on python.org about these failures. The multiprocessing module is still fairly new and obviously needs more fine tuning for...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....

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.