Add multiple body in email using python - python

I am trying to add multiple messages to email body but some how not able to do so.
#!/usr/intel/pkgs/python/2.7.2/bin/python
import sys
import argparse
import os
import time
import commands
import subprocess
import mmap
import sys
import argparse
import os.path
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
msg = MIMEMultipart()
monty_python = "monty_python.txt"
if(os.path.getsize(monty_python) > 0) is True:
text = "\n\n Cool !! some info found"
part1 = MIMEText(text,'plain')
with open(monty_python , 'r') as input_data:
thestring = input_data.read()
montystring = thestring[thestring.find('---------Monty Python-----'):]
e_mailthis = montystring[montystring.find('\n')+1:]
monty_log = MIMEText(e_mailthis,'plain')
print monty_log
else:
text = "No info found"
part1 = MIMEText(text,'plain')
msg.attach(part1)
msg.attach(monty_log)
print ("msg is %s")%(msg)
me = "my_email"
you = "receiptant's email"
msg['Subject'] = 'Monty Python info'
msg['From'] = "me"
msg['To'] = "you"
s = smtplib.SMTP('localhost')
s.sendmail(me, you, msg.as_string())
s.quit()
text file monty_python.txt
---------Monty Python-----
line1
line2
line3
with above code i am able to get email message but content of monty_python.txt files which i am trying to parse comes as an attachement but i am trying to get is as a body of email.
Any suggestions/input ?

Try this, send email from xxx#gmail.com to yyy#gmail.com
import smtplib
from email.mime.text import MIMEText
def send_email(content):
msg = MIMEText(content)
msg['Subject'] = 'Title'
msg['From'] = "xxx#gmail.com"
msg['To'] = "yyy#gmail.com"
s = smtplib.SMTP('smtp.gmail.com', 587)
s.ehlo()
s.starttls()
s.login("xxx#gmail.com", "password")
s.sendmail("xxx#gmail.com", "yyy#gmail.com", msg.as_string())
s.close()

Related

Python mailer dropping subjects from all except last in list

So I was working on an mail script to send mail to a list of users from text file. It works fine, iterating through the list, each user receives an email - except one detail, the subject is dropped from all emails except the last one sent by the script. What's happening here?
#!/usr/bin/env python
import sys
from smtplib import SMTP
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
targets = open('targets.txt', "rb")
def mailme():
for line in targets:
msg = MIMEMultipart('alternative')
m_source = '<sender#address.com>'
m_target = '%s' % line
smtp_server = 'mail.server.com'
smtp_port = '25'
msg['From'] = m_source
msg['To'] = m_target
msg['Subject'] = "Subject"
smtp = SMTP()
smtp.set_debuglevel(0)
smtp.connect(smtp_server, smtp_port)
message_text = ('Some Text for %s' % (m_target)
)
message_html = ("""<body>
<h1>Some HTML for %s</h1>
</body>"""
) % (m_target)
txt = MIMEText(message_text, 'plain')
web = MIMEText(message_html, 'html')
msg.attach(txt)
msg.attach(web)
smtp.sendmail(m_source, m_target, msg.as_string())
smtp.quit()
if __name__ == "__main__":
mailme()
sys.exit(0)
I suggested OP to put msg['Subject'] before msg['From'] and it solves the problem. I suggested because the python MIME email examples/tutorials all have msg['Subject'] comes before msg['From'] and msg['To'].
I thought it is a template to follow. If anyone knows of why this approach solves the problem please shed some light on this.

Attaching an s3 file to an smtplib lib email using MIMEApplication

I have a django application that would like to attach files from an S3 bucket to an email using smtplib and email.mime libraries.
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
# This takes the files and attaches each one within the bucket to the email. The server keeps erroring on the "with open(path,'rb') as fil" .
def attach_files(path_to_aws_bucket,msg,files=[]):
for f in files or []:
path = path_to_aws_bucket + f
with open(path,'rb') as fil:
msg.attach(MIMEApplication(
fil.read(),
Content_Disposition='attachment; filename="{}"' .format(os.path.basename(f)),
Name=os.path.basename(f)
))
return msg
def build_message(toaddress,fromaddress,subject,body):
msg = MIMEMultipart('alternative')
msg['To'] = toaddress
msg['From'] = fromaddress
msg['Subject'] = subject
b = u"{}" .format(body)
content = MIMEText(b.encode('utf-8') ,'html','UTF-8')
msg.attach(content)
return msg
def send_gmail(msg,username,password,fromaddress,toaddress):
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.login(username,password)
server.sendmail(fromaddress, toaddress , msg.as_string())
server.quit()
Python can't open the file because it claims that whatever s3 url I give it is not a valid directory. All of my permissions are correct. I tried using urllib.opener to open the file and attach it however it also threw an error.
Not sure where to go from here and was wondering if anyone has done this before. Thanks!
Have you considered using S3 get_object instead of smtplib?
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
import boto3
msg = MIMEMultipart()
new_body = "asdf"
text_part = MIMEText(new_body, _subtype="html")
msg.attach(text_part)
filename='abc.pdf'
msg["To"] = "amal#gmail.com"
msg["From"] = "amal#gmail.com"
s3_object = boto3.client('s3', 'us-west-2')
s3_object = s3_object.get_object(Bucket=‘bucket-name’, Key=filename)
body = s3_object['Body'].read()
part = MIMEApplication(body, filename)
part.add_header("Content-Disposition", 'attachment', filename=filename)
msg.attach(part)
ses_aws_client = boto3.client('ses', 'us-west-2')
ses_aws_client.send_raw_email(RawMessage={"Data" : msg.as_bytes()})
Using urllib works for me, look at the following, I have this Lambda function to send emails with smtplib:
import smtplib
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header
from email.utils import formataddr
import urllib
# ['subject','from', 'from_name','to','cc','body','smtp_server','smtp_user','smtp_password']
def lambda_handler(event, context):
msg = MIMEMultipart('alternative')
msg['Subject'] = event['subject']
msg['From'] = formataddr((str(Header(event['from_name'], 'utf-8')), event['from']))
msg['To'] = event['to']
msg['Cc'] = event['cc'] # this is comma separated field
# Create the body of the message (a plain-text and an HTML version).
text = "Look in a browser or on a mobile device this HTML msg"
html = event['body']
# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part1)
msg.attach(part2)
# Attach files from S3
opener = urllib.URLopener()
myurl = "https://s3.amazonaws.com/bucket_name/file_name.pdf"
fp = opener.open(myurl)
filename = 'file_name.pdf'
att = MIMEApplication(fp.read(),_subtype="pdf")
fp.close()
att.add_header('Content-Disposition','attachment',filename=filename)
msg.attach(att)
# Create de SMTP Object to Send
s = smtplib.SMTP(event['smtp_server'], 587)
s.login(event['smtp_user'], event['smtp_password'])
s.sendmail(msg['From'], [msg['To']], msg.as_string())
return True

Python how do i send multiple files in the email. I can send 1 file but how to send more than 1

I have the following code to send a html file SeleniumTestReport_part1.html in an email in Python.
I want to send more than 1 file in the email. How do can i do this?
The files I want to send are:
SeleniumTestReport_part1.html
SeleniumTestReport_part2.html
SeleniumTestReport_part3.html
My code to send 1 file is:
def send_selenium_report():
fileToSend = r"G:\test_runners\selenium_regression_test_5_1_1\TestReport\SeleniumTestReport_part1.html"
with open(fileToSend, "rt") as f:
text = f.read()
msg = MIMEText(text, "html")
msg['Subject'] = "Selenium ClearCore_Regression_Test_Report_Result"
msg['to'] = "4_server_dev#company.com"
msg['From'] = "system#company.com"
s = smtplib.SMTP()
s.connect(host=SMTP_SERVER)
s.sendmail(msg['From'], msg['To'], msg.as_string())
s.close()
Thanks,
Riaz
If you want to attach files to the email you can use just iterate over files and attach them to the message. You also may want to add some text to the body.
Here is the code:
import smtplib
import os
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
def send_selenium_report():
dir_path = "G:/test_runners/selenium_regression_test_5_1_1/TestReport"
files = ["SeleniumTestReport_part1.html", "SeleniumTestReport_part2.html", "SeleniumTestReport_part3.html"]
msg = MIMEMultipart()
msg['To'] = "4_server_dev#company.com"
msg['From'] = "system#company.com"
msg['Subject'] = "Selenium ClearCore_Regression_Test_Report_Result"
body = MIMEText('Test results attached.', 'html', 'utf-8')
msg.attach(body) # add message body (text or html)
for f in files: # add files to the message
file_path = os.path.join(dir_path, f)
attachment = MIMEApplication(open(file_path, "rb").read(), _subtype="txt")
attachment.add_header('Content-Disposition','attachment', filename=f)
msg.attach(attachment)
s = smtplib.SMTP()
s.connect(host=SMTP_SERVER)
s.sendmail(msg['From'], msg['To'], msg.as_string())
print 'done!'
s.close()
I have implemented this for sending mail from gmail.
import smtplib
from email.mime.text import MIMEText
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email import Encoders
def send_mail_gmail(username,password,toaddrs_list,msg_text,fromaddr=None,subject="Test mail",attachment_path_list=None):
s = smtplib.SMTP('smtp.gmail.com:587')
s.starttls()
s.login(username, password)
#s.set_debuglevel(1)
msg = MIMEMultipart()
sender = fromaddr
recipients = toaddrs_list
msg['Subject'] = subject
if fromaddr is not None:
msg['From'] = sender
msg['To'] = ", ".join(recipients)
if attachment_path_list is not None:
for each_file_path in attachment_path_list:
try:
file_name=each_file_path.split("/")[-1]
part = MIMEBase('application', "octet-stream")
part.set_payload(open(each_file_path, "rb").read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment' ,filename=file_name)
msg.attach(part)
except:
print "could not attache file"
msg.attach(MIMEText(msg_text,'html'))
s.sendmail(sender, recipients, msg.as_string())
You can pass multiple address as element of toaddrs_list to whom you want to send mail and multiple attachments files names with their path in attachment_path_list.

Send the contents of a CSV as a table in an email?

How can I send the contents of a CSV as a table in an email using Python?
Example file:
name,age,dob
xxx,23,16-12-1990
yyy,15,02-11-1997
you can use smtplib:
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
# just an example, you format it usng html
html = "<html><body><table><tr><td>name</td><td><age></td><td>dob</td<tr></table></body></html>"
msg1 = MIMEText(html,'html')
msg = MIMEMultipart("test")
msg['Subject'] = "Name of subject"
msg['From'] = "your#email.com"
msg['To'] = "reciver#gmail.com"
msg.attach(msg1)
server = smtplib.SMTP("smpt_server",port) # example smtplib.smtp("smtp.gmail.com,587)
server.starttls()
server.login("your#gmail.com","login_password")
server.sendmail("your#email.com","reciver#gmail.com",msg.as_string())
server.quit()
better you can do:
msg1 = MIMEText(f.open("file.csv").read())
msg.attach(msg1)
Check this link.
Just pass your csv as third argument to server.sendmail() method

Email module in python 3

So I'm following a tutorial to send email in python, the problem is that it was written for python 2 not python 3(which is what I have). So here's what I'm trying to get an answer what is the module for email in python 3? the specific module I'm trying to get is is:
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMETex
I also have a feelling that when I get down to this module there will be an error (haven't got there yet because of
the module above giving error
import smtp
Here is the script:
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMETex
fromaddr = ("XXXXX#mchsi.com")
toaddr = ("XXXX#mchsi.com")
msg = MIMEMultipart
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = ("test")
body = ("This is a test sending email through python")
msg.attach(MIMEText(body, ('plain')))
import smptlib
server = smptlib.SMPT('mail.mchsi.com, 456')
server.login("XXXXX#mchsi.com", "XXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
text = msg.as_string()
sender.sendmail(fromaddr, toaddr, text)
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
By the way here are some mistakes in your code:
fromaddr = "XXXXX#mchsi.com" # redundant parentheses
toaddr = "XXXX#mchsi.com" # redundant parentheses
msg = MIMEMultipart() # not redundant this time :)
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "test" # redundant parentheses
body = "This is a test sending email through python" # redundant parentheses
msg.attach(MIMEText(body, 'plain')) # redundant parentheses
import smtplib # SMTP! NOT SMPT!!
server = smtplib.SMTP('mail.mchsi.com', 456) # `port` is an integer
server.login("XXXXX#mchsi.com", "XXXXXXXXXXXXXXXXXXXXXXXXXXXXX") # on most SMTP servers you should remove domain name(`#mchsi.com`) here
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text) # it's not `sender`

Categories