i am new to python,and below is the code which is suppose to send mail to multiple receipent but only dipeshyog94#gmail.com is getting a mail. milanthapa898#gmail.com which is second on To and alexlee94#gmail.com which is on cc is no getting the mail
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
import smtplib
owner_emp_id_email = "dipeshyogi94#gmail.com,milanthapa989#gmail.com"
mymail='milanthapa898#gmail.com'
msg = MIMEMultipart()
msg['From'] = mymail
msg['To'] = owner_emp_id_email
cc_mail = "alexlee94#gmail.com"
msg['Cc'] = cc_mail
print('####44444444444444########\n')
print(owner_emp_id_email)
msg['Subject'] = 'Automated Test Mail with python'
a = 'Milan Thapa'
#body = 'Dear '+spoc_name+',\n\nYou have created new job with below Details:\n\nProject ID : '+project_ID+'\n\nProject Name : '+ibu_name+'\n\nJob Description : ' +job_description +'\n\nThanks and Regards,\n\nMilan Thapa'
html = """\
<html>
<head></head>
<body>
<p>'Dear <b>{}<b>
</p>
</body>
</html>
""".format(a)
msg.attach(MIMEText(html,'html'))
text = msg.as_string()
try:
server = smtplib.SMTP('smtp.gmail.com:587')
except:
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.ehlo()
server.login(mymail,'password')
server.sendmail(mymail,owner_emp_id_email,text)
server.quit()
i am stuck in this couldn't send the mail to multiple users.
any help will be greatly appreciated!
thanks in advance
The information in the headers doesn't control where the message actually goes. The second argument to sendmail is the only place where this is controlled. This value should be a list, not a comma-separated string.
owner_emp_id_email = "dipeshyogi94#gmail.com,milanthapa989#gmail.com"
env_rcpts = owner_emp_id_email.split(",")
# ...
cc_mail = "alexlee94#gmail.com"
env_rcpts.append(cc_mail)
# ...
server.sendmail(mymail,env_rcpts,text)
You'll notice that you could also add addresses which are neither in To: or Cc: (or a number of other headers which serve the same purpose) to effectively implement Bcc:
Maybe also look at send_message which saves you from having to separately convert your message to a string you can pass to sendmail.
msg['To'] = owner_emp_id_email
Here owner_emp_id_email is a string.
Make it a list of email ids. Then it would work.
to_ids = owner_emp_id_email.split(',')
msg['To'] = to_ids
>>> help(smtplib)
to_addrs: A list of addresses to send this mail to. A bare string will be treated as a list with 1 address.
You need to convert your CSV string to a list like mentioned in the the other answer. With this answer I just wanted to demonstrate how can we use the python's amazing help function when stuck.
Related
I am trying to send pandas dataframe via mail. I tried but I'm not able to obtain it. My code is
code
import pandas as pd
import json
import requests
from requests.auth import HTTPBasicAuth
import datetime
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import pdb
ticket_details=pd.DataFrame(list_values,
columns['incident',"short_description","priority","assignment_group"])
#converting a datframe into html table
df=ticket_details.to_html()
send ="xxx#xxx.com"
reciever="xxx#xxx.com"
subject="incident details "
msg = MIMEMultipart('alternative')
msg['From'] = send
msg['To'] = reciever
msg['Subject'] =subject
html_body = str(df)
messagePlain = 'Look at the incident details'
msg.attach(MIMEText(messagePlain, 'plain'))
msg.attach(MIMEText(html_body, 'html')
server = smtplib.SMTP("xxx.com")
server.sendmail(send, reciever, msg.as_string())
server.quit()
First of all please do not share personal information as mail address in your questions. Then the main problem is that you are converting your df to str and not to an html object.
# declare mixed MIME
msg = MIMEMultipart('mixed')
# convert df to html
table = df.to_html()
# attach to your mail
msg.attach(MIMEText(table, 'html')
Your HTML only contains a table and is not formatted as a full HTML page. But it reads correctly with Thunderbird. Anyway, I would add the minimum before and after the table to make it look like an acceptable HTML page:
...
prolog='''<html>
<head><title>Incident details</title></head>
<body>
'''
epilog = '</body></html>'
html_body = prolog + df + epilog
...
That is not a very nice HTML but at least, it has a html bloc, a header containing a title and a body. With that, it should be readable even on less tolerant mail readers.
I'm currently using the following code to send an email (which contains a report) to users 3 times per day. I'd like to add in a graph to this email but can't seem to figure out how.
def HTML_Email(subject, to, html, files, filename):
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from os.path import basename
import email
import email.mime.application
# Create message container - the correct MIME type is
multipart/alternative.
msg = MIMEMultipart('mixed')
msg['Subject'] = subject
msg['From'] = "ChicagoGISScripts#mobilitie.com"
msg['To'] = ", ".join(to)
# Record the MIME types of both parts - text/plain and text/html
part2 = MIMEText(html, 'html')
# create PDF attachment
fp=open(files,'rb')
att = email.mime.application.MIMEApplication(fp.read(),_subtype="xlsx")
fp.close()
att.add_header('Content-Disposition','attachment',filename=filename)
# Attach parts into message container.
msg.attach(att)
msg.attach(part2)
# Send the message via local SMTP server.
user = 'ausername'
pwd = 'apassword'
s = smtplib.SMTP('smtp.office365.com',587)
s.ehlo()
s.starttls()
s.ehlo()
s.login(user,pwd)
s.sendmail(msg['From'], to, msg.as_string())
s.quit()
Typically I'll use something like this to go along with it, but I'm trying to include a .png that's stored locally on my computer. is not working to embed an image into the body of the email, what am I missing here?
html = """\
<html>
<head></head>
<body>
<p><font face ="Gotham, monospace">Some HTML,<br><br>
<img src="C:\\Users\\Me\\Desktop\\graphs.png"></img></font>
</p>
</body>
</html>
"""
Because you aren't hosting the image on a server, you won't be able to embed it in an email using a normal link. Try encoding the .png file into a data uri and setting that as the src
EDIT
Look at this other answer to see how to do this in python
EDIT 2
The resulting html should look like this
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot" />
Exactly what RemedialBear said. You have to host the email on a server and have an absolute src in your email body.
Instead of:
<img src="C:\\Users\\Me\\Desktop\\graphs.png">
You need:
<img src="http://www.somedomain.com/images/graphs.png" alt="Name' />
I've got a script that sends emails with html content in them.. works as expected...
I'm having trouble sending an attachment with the email.
The attachment is an html file stored in the active directory of the script... "test.html"
How do I attach the html file to the email? I've tried snippets from various other posts I've found relating to this, but each returned the same output of "no such file or directory".
code as follows:
import smtplib
import os
import email.encoders
import email.mime.text
import email.mime.base
import mimetools
import base64
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# me == Outgoing email address
# you == Recipient's email address
me = "secret"
you = "secret"
# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = "TEST"
msg['From'] = me
msg['To'] = you
emailMsg = email.MIMEMultipart.MIMEMultipart('alternative')
# Create the body of the message (a plain-text and an HTML version).
html = """\
<html>
<head></head>
<body>test</p>
</body>
</html>"""
# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
filename = "C:/CHRIS/ServerStatus/Oceaneering_Server_Status.html"
f = file(filename)
attachment = MIMEText(f.read(), _subtype='html')
attachment.add_header('Content-Disposition', 'attachment', filename=filename)
# 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)
msg.attach(attachment)
# Send the message via local SMTP server.
mail = smtplib.SMTP('smtp.gmail.com', 587)
mail.ehlo()
# mail.login(username, password) to Outgoing email account
mail.login('secret', 'secret')
mail.sendmail(me, you, msg.as_string())
mail.quit()
i've updated my code in hopes to get this question back on topic... i've made a little progress with the help of Dirk and this link:
Attach a txt file in Python smtplib...
I've been able to physically send an attachment now, but the attachment is still coming through as a text type of file of sort and does not open as the original html file does.
So to reword my question... What is the corrective action for changing the MIME type of this code to correctly attach an .html file to an html based email?
The relative path and directory of my py script and the html file needed to be sent is as follows:
C:\CHRIS\ServerStatus\
This is the output i'm receiving with the code I have:
This is the way the html doc looks outside of the email script (The way it's supposed to look):
I would encourage you to use a library rather than deal with the -rather unpythonic- built-in mail modules, such as the highly recommended envelopes:
https://tomekwojcik.github.io/envelopes/index.html
install with:
pip install envelopes
Python code:
import os
from envelopes import Envelope
filename = "C:/CHRIS/ServerStatus/Oceaneering_Server_Status.html"
envelope = Envelope(
from_addr=(me),
to_addr=(you),
subject=u'Test',
text_body=u'Plain text version',
html_body=html
)
envelope.add_attachment(filename)
envelope.send('smtp.gmail.com', login='secret', password='secret', tls=True)
Email With Mandrill to multiple emailId but it only deliver to id which is first in the list to rest it does not send.I want to send mail to multiple users using mandrill API
here is my code :
class mandrillClass:
def mandrillMail(self,param):
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
msg = MIMEMultipart('alternative')
msg['Subject'] = param['subject']
msg['From'] = param['from']
msg['To'] = param['to']
html = param['message']
print html
text = 'dsdsdsdds'
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
username = 'xyz#gmail.com'
password = 'uiyhiuyuiyhihuohohio'
msg.attach(part1)
msg.attach(part2)
s = smtplib.SMTP('smtp.mandrillapp.com', 587)
s.login(username, password)
s.sendmail(msg['From'], msg['To'], msg.as_string())
s.quit()
and here i am calling the function
from API_Program import mandrillClass
msgDic = {}
msgDic['subject'] = "testing"
msgDic['from'] = "xyz#gmail.com"
#msgDic['to'] = 'abc#gmail.com','example#gmail.com'
COMMASPACE = ', '
family = ['abc#gmail.com','example#gmail.com']
msgDic['to'] = COMMASPACE.join(family)
msgDic['message'] = "<div>soddjags</div>"
mailObj = mandrillClass()
mailObj.mandrillMail(msgDic)
Since you're using smtplib, you'll want to review the documentation for that SMTP library on how you specify multiple recipients. SMTP libraries vary in how they handle multiple recipients. Looks like this StackOverflow post has information about passing multiple recipients with smtplib: How to send email to multiple recipients using python smtplib?
You need a list instead of just strings, so something like this:
msgDic['to'] = ['abc#gmail.com','example#gmail.com']
So, your family variable is declared properly, and you shouldn't need to do anything to that.
Try:
msgDic['to'] = [{"email":fam} for fam in family]
From the docs it looks like they expect this structure:
msgDic['to'] = [ {"email":"a#b.c", "name":"a.b", "type":"to"},
{"email":"x#y.z", "name":"x.z", "type":"cc"}
]
where you can omit name and type.
I'm creating some emails in Python and I'd like to have HTML, text, and an attachment. My code is 'working', though its outputs are shown by Outlook as EITHER HTML or text, while showing the other 'part' (email or txt) as an attachment. I'd like to have the robust-ness of both email and text versions along with the file attachment.
Is there a fundamental limitation or am I making a mistake?
#!/usr/bin/env python3
import smtplib,email,email.encoders,email.mime.text,email.mime.base
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# me == my email address
# you == recipient's email address
me = "me#me.com"
you = "you#you.com"
# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('mixed')
msg['Subject'] = "msg"
msg['From'] = me
msg['To'] = you
# Create the body of the message (a plain-text and an HTML version).
text = "Hi\nThis is text-only"
html = """\
<html> This is email</html>
"""
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
#attach an excel file:
fp = open('excelfile.xlsx', 'rb')
file1=email.mime.base.MIMEBase('application','vnd.ms-excel')
file1.set_payload(fp.read())
fp.close()
email.encoders.encode_base64(file1)
file1.add_header('Content-Disposition','attachment;filename=anExcelFile.xlsx')
# 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(part2)
msg.attach(part1)
msg.attach(file1)
composed = msg.as_string()
fp = open('msgtest.eml', 'w')
fp.write(composed)
fp.close()
I found this has in fact been answered. Strange how the search feature is less effective than the 'related' boxes.
Sending Multipart html emails which contain embedded images