adding attachment using sendmail from unix
Sendmail is an extremely simplistic program. It knows how to send a blob of text over smtp. If you want to have attachments, you're going to have to do the work of converting them into a blob of text and using (in your example) p.write() to add them into the message.
That's hard - but you can use the email
module (part of python core) to do a lot of the work for you.
Even better, you can use smtplib
(also part of core) to handle sending the mail.
Check out http://docs.python.org/2/library/email-examples.html#email-examples for a worked example showing how to send a mail with attachments using email
and smtplib
Use the email.mime
package to create your mail instead of trying to generate it manually, it will save you a lot of trouble.
For example, sending a text message with an attachment could be as simple as:
from email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextfrom email.mime.application import MIMEApplicationmsg = MIMEMultipart()msg['From'] = 'fromaddress'msg['To'] = 'toaddres'msg['Subject'] = 'subject'msg.attach(MIMEText('your text message'))with open(filename, 'rb') as f: attachment = MIMEApplication(f.read(), 'subtype') attachment['Content-Disposition'] = 'attachment; filename="%s";' % filename msg.attach(attachment)message = msg.as_string()
Then you can write the message to sendmail, or use smtplib to send it.
'subtype'
should either be replaced with the mime subtype of the attached document, or left out to send the attachment with the default type of application/octet-stream
. Or if you know your file is text, you can use MIMEText
instead of MIMEApplication
.
I normally use the following to send a file "file_name.dat" as attachment:
uuencode file_name.dat file_name.dat | mail -s "Subject line" arnab.bhagabati@gmail.com