Using SMTPlib.

Wen Jiang wj691781 at bcm.tmc.edu
Mon Jun 4 12:46:46 EDT 2001


I have a function which might be just what you need.

Wen

def SendMail(to="",subject="Your Subject",msg="",images=[]):
	import smtplib, socket, StringIO, MimeWriter, base64
	fromaddr=os.environ["USER"]+"@"+socket.gethostname()
	if not to: 
		to=fromaddr
		tos=[[to,'']]
	else:
		import re
	
mailaddrp=re.compile(r"([A-Za-z0-9._-]+@[A-Za-z0-9_-]+(\.[A-Za-z0-9_-]+)*)")
		tos=mailaddrp.findall(to)
	server = smtplib.SMTP('localhost')
	server.set_debuglevel(0)
	for cto in tos:
		outputfp = StringIO.StringIO()
		
		# Create a MimeWriter object
		
		w = MimeWriter.MimeWriter(outputfp)
		w.addheader("Subject", subject)
		w.addheader("To", cto[0])
		w.addheader("MIME-Version", "1.0")
		w.flushheaders()
		
		# Now we create a plain text segment and write the instructions file
into it
		
		w.startmultipartbody("mixed")
		instructions = w.nextpart()
		instFile = instructions.startbody("text/plain")
		instructions.flushheaders()
		instFile.write(msg)
		
		# Now we create a base64 encoded segment and write the diary file into
it
		
		# as an attachment
		if images:
			for img in images:
				subwriter = w.nextpart()
				subwriter.addheader("Content-Transfer-Encoding", "base64")
				subwriter.addheader("Content-Disposition", 'inline; filename="%s"' %
img)
				f = subwriter.startbody('application/octet-stream; name="%s"' % img)
				subwriter.flushheaders()
				f.write(base64.encodestring(open(img, 'rb').read()))
		w.lastpart()
		server.sendmail(fromaddr, cto[0], outputfp.getvalue())
	server.close()

Brian Andersen wrote:
> 
> Hi.
> 
> I'm in the process of writing my very first project in Python - a webmail
> application.
> I've tried the SMTPlib and it work out fint, but the mails I send don't have
> a subject.
> 
> I've tried the example that is in the Pythondocumentation for the SMTPlib
> and it works well, but how do I insert a subject field?
> 
> The same goes for CC end BCC-fields. Are they handled by the SMTPlib or is
> it something that I must handle in my program?
> 
> Hope you can help me.
> 
> Best regards.
> Brian.



More information about the Python-list mailing list