Send an attachment using Python script - python

I used following python script to send an attachment through gmail. But it can be used for send an attachment which is saved in the same folder python script is saved. I want to send an attachment which is saved in different folder. How can I do it by modifing this script? Thank you.
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders
import os
import datetime
smtpUser = ' '
smtpPass = ' '
toAdd = ' '
fromAdd = smtpUser
today = datetime.date.today()
subject = 'Data File 01 %s' % today.strftime('%Y %b %d')
header = 'To :' + toAdd + '\n' + 'From : ' + fromAdd + '\n' + 'Subject : ' + subject + '\n'
body = 'This is a data file on %s' % today.strftime('%Y %b %d')
attach = 'Data on %s.csv' % today.strftime('%Y-%m-%d')
print header
def sendMail(to, subject, text, files=[]):
assert type(to)==list
assert type(files)==list
msg = MIMEMultipart()
msg['From'] = smtpUser
msg['To'] = COMMASPACE.join(to)
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = subject
msg.attach( MIMEText(text) )
for file in files:
part = MIMEBase('application', "octet-stream")
part.set_payload( open(file,"rb").read() )
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"'
% os.path.basename(file))
msg.attach(part)
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo_or_helo_if_needed()
server.starttls()
server.ehlo_or_helo_if_needed()
server.login(smtpUser,smtpPass)
server.sendmail(smtpUser, to, msg.as_string())
print 'Done'
server.quit()
sendMail( [toAdd], subject, body, [attach] )

The fourth parameter of sendMail is a list of filenames, so you can do e.g.:
sendMail(["name#domain.com"],
"Subject",
"Dear sir..",
["subdir/file1.zip", "subdirfile.zip"] )
whereas subdir/file1.zip is relative to the path where you call the script. If you want to refer to a file somewhere completely else use /path/to/my/file1.zip, e.g. /home/user/file1.zip

Related

python email multiple receiver, multiple attachment for error

def mail():
import os
import pandas as pd
import smtplib
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.utils import formatdate
from email.mime.multipart import MIMEMultipart
from email import encoders
from PyQt5.QtCore import QDate, Qt
path = 'C:/Users/user/Desktop/pdf/'
contact = 'con1.xlsx'
df = pd.read_excel(str(path)+contact, endcoding ='utf8')
df.set_index('unyong', inplace = True)
now = QDate.currentDate()
filenm = [f for f in os.listdir(path) if f.endswith('.pdf')]
unyong_nm = []
for w in filenm:
a = w.find('_')
b = w.rfind('_')
unyong_nm.append(w[a+1:b])
unyong_nm = list(set(unyong_nm))
for i in range(0,len(unyong_nm)):
send_from = 'ss#ddd'
recipients = df.loc[unyong_nm[i],'email']
send_to = ",".join(recipients)
attach = [s for s in filenm if s.find(unyong_nm[i]) >-1 ]
username = 'sss#ssss'
password = 'sss'
subject = ('111'+now.toString('yyyy.MM')+'_'+unyong_nm[i]+str(i+1))
text = ('hi')
msg = MIMEMultipart()
msg['From'] = send_from
msg['To']= send_to
msg['Subject'] = subject
msg['Date']=formatdate(localtime=True)
filename_match = [s for s in filenm if s.find(unyong_nm[i]) >-1 ]
for file in filename_match:
part =MIMEBase('application','octet-stream')
part.set_payload(open(str(path)+file, 'rb').read())
encoders.encode_base64(part)
part.add_header('Content-Disposition','attachment', filename =file)
msg.attach(part)
msg.attach(MIMEText(text))
mailServer = smtplib.SMTP("smtp.sssss.com", 587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(username,password)
mailServer.sendmail(send_from, send_to, msg.as_string())
mailServer.close()
hi i have a problem with the email with attachment for statement.
the results of below def mail(),
multiple emails was sent to one person. (<- this is a error)
I want to send a each specific reciever with specific multiple attachments only once
why multiple email sented with diffrent number of attachements to one person.
the reciever have the 2 emails with a 1 attachment and, simultaneouly 2 attachment.
I want to send a email containg 2 attachments
please help me.
*CF) path containg thoes files:
['2221_sss_love.pdf', '2221_sss_happy.pdf', '2221_ddd_sad.pdf', '2221_ddd_lucky.pdf', 'con1.xlsx']
*result
unyong_nm = ['sss','ddd']
filenm = ['2221_sss_love.pdf', '2221_sss_happy.pdf', '2221_ddd_sad.pdf', '2221_ddd_lucky.pdf']
*CF) con1.xlsx file contenxt:
unyong email
sss 111#aaa
sss 777#bbb
ddd 666#sss
ddd 444#ccc
The code is sending an email for each attachment. By dedenting the mail-sending code, an email will be sent for each set of attachments grouped by 'ddd' or 'sss'.
for file in filename_match:
part = MIMEBase("application", "octet-stream")
part.set_payload(open(file, "rb").read())
encoders.encode_base64(part)
part.add_header("Content-Disposition", "attachment", filename=file)
msg.attach(part)
msg.attach(MIMEText(text))
# Send mail outside the file grouping loop
mailServer = smtplib.SMTP("localhost", 1025)
mailServer.ehlo()
mailServer.sendmail(send_from, send_to, msg.as_string())
mailServer.close()
The recipient selection code
recipients = df.loc[unyong_nm[i],'email']
send_to = ",".join(recipients)
might need to be changed, I can't tell because the contents of the dataframe aren't provided in the question.

Sending an attachment in mail using a variable as data container python

I'd like to know if it was possible to send a variable (say a string) as an attachment in a mail using python. The goal is to avoid the making of temporary files in the process.
As an example, I'd like to send a string which is formatted as a csv as an attachment to a mail and possibly this attachment could later be downloaded as a file on the other end of the tunnel.
Thanks for all of your possible help.
EDIT: It now works with StringIO, thank you for your help. Answer below
So here's the working method that I am now using:
#!/usr/bin/python2.7.x
# -*- coding: utf-8 -*-
#Imports
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase
from email import encoders
from email.Utils import COMMASPACE, formatdate
import sys
try:
from StringIO import StringIO
except:
print("Could not import critical library StringIO")
sys.exit(0)
import smtplib
import datetime
def run_mail(self):
date = datetime.datetime.now()
dateAAAAMMDD = str(date.year) + "_" + str( date.month) + "_" +str( date.day)
pj1 = StringIO(self.pj1_data)
pj1_name = "my_att_name_" + str(dateAAAAMMDD) + ".csv"
pj2 = StringIO(self.pj2_data)
pj2_name = "my_att_name2_" + str(dateAAAAMMDD) + ".txt"
pj3 = StringIO(self.pj3_data)
pj3_name = "my_att_name3_" + str(dateAAAAMMDD) + ".txt"
pj =[(pj1,pj1_name), (pj2,pj2_name), (pj3,pj3_name)]
fromaddr = 'address#something.com'
toaddr = 'toanotheraddress#something.com'
msg = MIMEMultipart()
subject = 'subject dated ' + dateAAAAMMDD
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = subject
msg.attach(MIMEText("Auto-generated script", 'plain'))
for data, att_name in pj :
part = MIMEBase('application', 'octet-stream')
part.set_payload(data.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename= "%s"' % att_name)
msg.attach(part)
server_port = 25
server = smtplib.SMTP('myserver.com',server_port)
server.starttls()
#If login required, not very secure, use either input or localhost without
#login required
server.login(fromaddr, 'MyPasswordGoesHere')
content = msg.as_string()
server.sendmail(fromaddr,toaddr,content)
server.quit()

Sending an e-mail with excel attachment but the excel sheet is corrupted. what do i do?

command to send e-mail : scripts/emailSendWithAttachment.py '' '' '' 'Daily Report' '' $latestFileName
Although the E-mail is being sent, it says the excel attachment is corrupted and cannot be opened. I am pasting the code here so that you guys can take a look.
emailSendWithAttachment.py :
import os
import sys
import csv
import json
import logging
from datetime import datetime,timedelta
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from subprocess import Popen, PIPE
logging.basicConfig(format='[%(asctime)s]: [%(name)s]: [%(levelname)-4s] %(message)s',
datefmt = '%Y-%m-%d %H:%M:%S', level = logging.INFO
)
# Get the total number of args passed to the demo.py
total = len(sys.argv)
print " Total :" + str(total)
print str(sys.argv[0]) +" " + str(sys.argv[1]) + " " + str(sys.argv[3]) +" " +str(sys.argv[4]) +" " + str(sys.argv[6])
if( total != 7):
print ("The total numbers of args should be 6 as EMAIL_FROM,EMAIL_TO,subject,body,Tgt_Dir,File_Name[]")
sys.exit(0)
if(datetime.now().strftime("%A") == 'Monday'):
iDate = (datetime.now()+timedelta(days=-3)).strftime('%Y%m%d')
else:
iDate = (datetime.now()+timedelta(days=-1)).strftime('%Y%m%d')
print iDate
EMAIL_FROM = str(sys.argv[1])
EMAIL_TO = str(sys.argv[2])
subject=str(sys.argv[3]) + iDate
body=str(sys.argv[4]) + iDate
Tgt_Dir =str(sys.argv[5])
File_Name=sys.argv[6]
fileNameArray=File_Name.split(',')
def sendMailMime(emailFrom,emaiTo,subject, body, tgtdir,filename):
msg = MIMEMultipart()
msg['From'] = emailFrom
msg['To'] = emaiTo
msg['Subject'] = subject
msg.attach(MIMEText(body))
print filename
for file in filename :
print file
payload = os.path.join(tgtdir, file)
with open(payload, 'rb') as f:
attachment = MIMEText(f.read())
attachment['Content-Disposition'] = 'attachment; filename="%s"' % os.path.basename(payload)
msg.attach(attachment)
message = msg.as_string()
p = Popen(["/usr/sbin/sendmail", "-t"], stdin=PIPE)
p.communicate(message)
sendMailMime(EMAIL_FROM,EMAIL_TO,subject,body,Tgt_Dir,fileNameArray)

Mail is going out 3 times instead of once to each address?

I have come up with something which seems weird to me and I am not sure what exactly to search for.
import smtplib, openpyxl, sys
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
wb = openpyxl.load_workbook('Book1.xlsx')
sheet = wb.get_sheet_by_name('Sheet1')
lastCol = sheet.max_column
latestMonth = sheet.cell(row=1, column=lastCol).value
recipients = []
unpaidMembers = {}
for r in range(2, sheet.max_row + 1):
payment = sheet.cell(row=r, column=lastCol).value
if payment != 'Y':
name = sheet.cell(row=r, column=1).value
email = sheet.cell(row=r, column=2).value
unpaidMembers[name] = email
recipients.append(email)
fromaddr = "xxxx#xxxx.com"
for n in recipients:
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = n
msg['Subject'] = "Hi"
body = "This is a test mail"
msg.attach(MIMEText(body, 'plain'))
filename = "xxx.pdf"
attachment = open("\\Users\xxx\xxx\xxx.pdf","rb")
part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % filename)
msg.attach(part)
smtp0bj = smtplib.SMTP('smtp-mail.outlook.com', 587)
smtp0bj.ehlo()
smtp0bj.starttls()
smtp0bj.login(fromaddr, 'xxxxx')
text = msg.as_string()
smtp0bj.sendmail(fromaddr, recipients, text)
smtp0bj.quit()
I am guessing that the for-loop is being executed 3 times(there are 3 items in the list. I am at a loss about how to make it execute only once.
You basically do that :
for n in recipients: # for each recipient
smtp0bj.sendmail(fromaddr, recipients, text) # send mail to all recipients
So at each pass it sends the mail to all the recipients.
So if you have 3 recipients, they'll receive 3 mails each.
Replace with :
smtp0bj.sendmail(fromaddr, n, text)
Also I'm not sure, and can't test right now, but I believe 'to' has to be a list.
So if the above solution doesn't work, give this a shot :
smtp0bj.sendmail(fromaddr, [n], text)

Python SMTP/MIME Message body

I've been working on this for 2 days now and managed to get this script with a pcapng file attached to send but I cannot seem to make the message body appear in the email.
import smtplib
import base64
import ConfigParser
#from email.MIMEapplication import MIMEApplication
#from email.MIMEmultipart import MIMEMultipart
#from email.MIMEtext import MIMEText
#from email.utils import COMMASPACE, formatdate
Config = ConfigParser.ConfigParser()
Config.read('mailsend.ini')
filename = "test.pcapng"
fo = open(filename, "rb")
filecontent = fo.read()
encoded_content = base64.b64encode(filecontent) # base 64
sender = 'notareal#email.com' # raw_input("Sender: ")
receiver = 'someother#fakeemail.com' # raw_input("Recipient: ")
marker = raw_input("Please input a unique set of numbers that will not be found elsewhere in the message, ie- roll face: ")
body ="""
This is a test email to send an attachment.
"""
# Define the main headers
header = """ From: From Person <notareal#email.com>
To: To Person <someother#fakeemail.com>
Subject: Sending Attachment
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=%s
--%s
""" % (marker, marker)
# Define message action
message_action = """Content-Type: text/plain
Content-Transfer-Encoding:8bit
%s
--%s
""" % (body, marker)
# Define the attachment section
message_attachment = """Content-Type: multipart/mixed; name=\"%s\"
Content-Transfer-Encoding:base64
Content-Disposition: attachment; filename=%s
%s
--%s--
""" % (filename, filename, encoded_content, marker)
message = header + message_action + message_attachment
try:
smtpObj = smtplib.SMTP('smtp.gmail.com')
smtpObj.sendmail(sender, receiver, message)
print "Successfully sent email!"
except Exception:
print "Error: unable to send email"
My goal is to ultimately have this script send an email after reading the parameters from a config file and attach a pcapng file along with some other text data describing the wireshark event. The email is not showing the body of the message when sent. The pcapng file is just a test file full of fake ips and subnets for now. Where have I gone wrong with the message body?
def mail_man():
if ms == 'Y' or ms == 'y' and ms_maxattach <= int(smtp.esmtp_features['size']):
fromaddr = [ms_from]
toaddr = [ms_sendto]
cc = [ms_cc]
bcc = [ms_bcc]
msg = MIMEMultipart()
body = "\nYou're captured event is attached. \nThis is an automated email generated by Dumpcap.py"
msg.attach("From: %s\r\n" % fromaddr
+ "To: %s\r\n" % toaddr
+ "CC: %s\r\n" % ",".join(cc)
+ "Subject: %s\r\n" % ms_subject
+ "X-Priority = %s\r\n" % ms_importance
+ "\r\n"
+ "%s\r\n" % body
+ "%s\r\n" % ms_pm)
toaddrs = [toaddr] + cc + bcc
msg.attach(MIMEText(body, 'plain'))
filename = "dcdflts.cong"
attachment = open(filename, "rb")
if ms_attach == 'y' or ms_attach == "Y":
part = MIMEBase('application', 'octet-stream')
part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % filename)
msg.attach(part)
server = smtplib.SMTP(ms_smtp_server[ms_smtp_port])
server.starttls()
server.login(fromaddr, "YOURPASSWORD")
text = msg.as_string()
server.sendmail(fromaddr, toaddrs, text)
server.quit()
This is my second attempt, all "ms_..." variables are global through a larger program.
You shouldn't be reinventing the wheel. Use the mime modules Python has included in the standard library instead of trying to create the headers on your own. I haven't been able to test it out but check if this works:
import smtplib
import base64
import ConfigParser
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
filename = "test.pcapng"
with open(filename, 'rb') as fo:
filecontent = fo.read()
encoded_content = base64.b64encode(filecontent)
sender = 'notareal#email.com' # raw_input("Sender: ")
receiver = 'someother#fakeemail.com' # raw_input("Recipient: ")
marker = raw_input("Please input a unique set of numbers that will not be found elsewhere in the message, ie- roll face: ")
body ="""
This is a test email to send an attachment.
"""
message = MIMEMultipart(
From=sender,
To=receiver,
Subject='Sending Attachment')
message.attach(MIMEText(body)) # body of the email
message.attach(MIMEApplication(
encoded_content,
Content_Disposition='attachment; filename="{0}"'.format(filename)) # b64 encoded file
)
try:
smtpObj = smtplib.SMTP('smtp.gmail.com')
smtpObj.sendmail(sender, receiver, message)
print "Successfully sent email!"
except Exception:
print "Error: unable to send email"
I've left off a few parts (like the ConfigParser variables) and demonstrated only the email related portions.
References:
How to send email attachments with Python
Figured it out, with added ConfigParser. This is fully functional with a .ini file
import smtplib
####import sys#### duplicate
from email.parser import Parser
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
import ConfigParser
def mail_man(cfg_file, event_file):
# Parse email configs from cfg file
Config = ConfigParser.ConfigParser()
Config.read(str(cfg_file))
mail_man_start = Config.get('DC_MS', 'ms')
security = Config.get('DC_MS', 'ms_security')
add_attachment = Config.get('DC_MS', 'ms_attach')
try:
if mail_man_start == "y" or mail_man_start == "Y":
fromaddr = Config.get("DC_MS", "ms_from")
addresses = [Config.get("DC_MS", "ms_sendto")] + [Config.get("DC_MS", "ms_cc")] + [Config.get("DC_MS", "ms_bcc")]
msg = MIMEMultipart() # creates multipart email
msg['Subject'] = Config.get('DC_MS', 'ms_subject') # sets up the header
msg['From'] = Config.get('DC_MS', 'ms_from')
msg['To'] = Config.get('DC_MS', 'ms_sendto')
msg['reply-to'] = Config.get('DC_MS', 'ms_replyto')
msg['X-Priority'] = Config.get('DC_MS', 'ms_importance')
msg['CC'] = Config.get('DC_MS', 'ms_cc')
msg['BCC'] = Config.get('DC_MS', 'ms_bcc')
msg['Return-Receipt-To'] = Config.get('DC_MS', 'ms_rrr')
msg.preamble = 'Event Notification'
message = '... use this to add a body to the email detailing event. dumpcap.py location??'
msg.attach(MIMEText(message)) # attaches body to email
# Adds attachment if ms_attach = Y/y
if add_attachment == "y" or add_attachment == "Y":
attachment = open(event_file, "rb")
# Encodes the attachment and adds it to the email
part = MIMEBase('application', 'octet-stream')
part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename = %s" % event_file)
msg.attach(part)
else:
print "No attachment sent."
server = smtplib.SMTP(Config.get('DC_MS', 'ms_smtp_server'), Config.get('DC_MS', 'ms_smtp_port'))
server.ehlo()
server.starttls()
if security == "y" or security == "Y":
server.login(Config.get('DC_MS', 'ms_user'), Config.get('DC_MS', 'ms_password'))
text = msg.as_string()
max_size = Config.get('DC_MS', 'ms_maxattach')
msg_size = sys.getsizeof(msg)
if msg_size <= max_size:
server.sendmail(fromaddr, addresses, text)
else:
print "Your message exceeds maximum attachment size.\n Please Try again"
server.quit()
attachment.close()
else:
print "Mail_man not activated"
except:
print "Error! Something went wrong with Mail Man. Please try again."

Categories