473,657 Members | 2,385 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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(f ilename,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.rea d(),_subtype=su btype)
elif maintype == 'message' and subtype ==
"rfc822":
attach = email.message_f rom_file(fp)
attach = MIMEMessage(att ach)
elif maintype == 'message' and subtype <>
"rfc822":
attach = email.message_f rom_file(fp)
elif maintype == 'image':
attach = MIMEImage(fp.re ad(),_subtype=s ubtype)
elif maintype == 'audio':
attach = MIMEAudio(fp.re ad(),_subtype=s ubtype)
else:
#print maintype, subtype #if it does not
equal any of the
#above we print to screen and encode and
return
attach = MIMEBase(mainty pe, subtype) #the
encoded value
attach.set_payl oad(fp.read())
encode_base64(a ttach)

fp.close()
filename = os.path.basenam e(filename)
attach.add_head er('Content-Disposition',
'attachment',fi lename=filename )
return attach

#This function base I try to build email message
def create_mail(dom ain, user, form, from_name):
to = cc = bcc = subject = body = ''
attachments = []
send_addresses = ''
if form.has_key('t o'):
to = form['to'].value.strip()
send_addresses = to
if form.has_key('c c'):
cc = form['cc'].value.strip()
send_addresses = to + ',' + cc
if form.has_key('b cc'):
bcc = form['bcc'].value.strip()
send_addresses = to + ',' + cc + ',' + bcc
if form.has_key('s ubject'): subject =
form['subject'].value
if form.has_key('b ody'): body = form['body'].value
if form.has_key('a ttachments[]'): attachments =
form.getlist("a ttachments[]")

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(loca ltime=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(loca ltime=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(f ilename,att_typ e):
attach =
addAttachment(f ilename,att_typ e)
msg.attach(atta ch)

# 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 2395
On Sat, 6 Aug 2005 08:45:30 +0100 (BST), praba kar <pr*********@ya hoo.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(dom ain, 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(dom ain, 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
2096
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 page. http://www.dafella.com/xeoport/ The original coder left no contact info. The reason I think it's the code is because of another issue.
0
2410
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 narrowed it down to the Scrubber.py file.. If this seems like a quick step me through, I would be very appreciative, could get you something on your Amazon wish-list (that is me on my knees begging).. From just my basic understanding, it...
0
1191
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 /home/miallen/Maildir/.Lists.Expat: I would have archived 113 of 116 message(s) in 0.3 seconds /home/miallen/Maildir/.Lists.JCIFS: I would have archived 628 of 1796 message(s) in 4.2 seconds /home/miallen/Maildir/.Lists.Jarapac: I would have archived 0 of 6
1
1792
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 pointer. I don't want to use rfc822.Message. I'd like to use mhlib.Message instead.
1
1467
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 easily enough, (and intend to if nothing exists) but before I do, I am looking for anything that already exists and is either a standard or is already in common use. Google turned up a few odds and ends, the most definitive being a series of...
4
1415
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 field: Date: Tue,26 Jul 2005 13:14:27 GMT +0200 It seems to be correct¹, but parsedate_tz is not able to decode it, it is confused by the absence of a space after the ",".
7
1453
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 copy built outputs to the Web. Unable to add 'C:\Documents and Settings\dyoung.BFGPDC\VSWebCache\DAL_DYOUNG\\bin\.pdb' to the project. The server connection timed out. The dll representing the class library is copied correctly and both the dll...
4
2295
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 as the sample. I have trouble translating those samples to working with data coming from my database, so I am hoping that someone could show me a sample of code that builds a tree from say a dataset. Many controls you can bind to a datasource,...
0
1518
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 the large set of platforms on which Python can run. However, please also note that FreeBSD4 is a rather old version of that OS. FWIW: Python 2.6 compiles just fine on FreeBSD6. Thanks.
0
8842
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8740
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...
1
8516
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8617
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
7353
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...
0
5642
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
4173
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...
0
4330
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2743
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

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.