I'm trying to send emails to people in a distribution list in my company using python. My company uses outlook.
When I send to individual users specifying their email, it works perfectly. However I need to use the distribution list, since the recipients are updated by my IT department and I cant keep updating the email list whenever it changes.
Whomever has used outlook, you might recall that the distribution list starts with an exclamation mark like so: !groupdept#company.com
I am using the following method to send emails using python:
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from smtplib import SMTP
import smtplib
import sys
subject = "Group Email"
fromm = 'me#company.com'
recipients = ['someone#company.com, someonelse#company.com']
emaillist = [elem.strip().split(',') for elem in recipients]
msg = MIMEMultipart()
msg['Subject'] = subject
msg['From'] = fromm
html = """\
<html>
<head>
</head>
<body style="font-size:18px;">
{0}
</body>
</html>
""".format(df2.style
.set_properties(**{'border': '2.5pt solid green', 'color': 'magenta', 'font-size': '15pt'})
.hide_index()
.hide_columns()
.render()
)
message = MIMEText(html, 'html')
msg.attach(message)
server = smtplib.SMTP('00.0.0.00', 25)
server.sendmail(msg['From'], emaillist , msg.as_string())
The above method works well for comma separated recipients. However if I use !groupdept#company.com it doesn't work, which I can understand since that is an MS Outlook functionality.
Has anyone achieved this before?
Related
I created a script in python to email with an attachment. I put it in databricks, and put it on a schedule. When I manually run this function, it fires only one email, but when it runs on the schedule, to emails are sent to each recipient. Although it sounds like a schedule issue, I believe it's a code issue - I was able to get it to work at some point, but now it is sending again.
If anyone can take a look at the code below and see if they can figure out why it would be duplicating, it would be appreciated!
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from datetime import date
def SendEmail(recipient, subject,message_records,attach,cc,bcc,df):
server = smtplib.SMTP ('smtp.sendgrid.net', 587) # check server and port with your provider
server.ehlo()
server.starttls()
server.login("apikey", dbutils.secrets.get(scope = "XXXX", key = "XXXX")) # insert secret name
sender = dbutils.secrets.get(scope = "XXXX", key = "XXXX") # insert secret name
msg = MIMEMultipart()
msg['Subject'] = subject
msg['From'] = "noreply#noreply.com"
msg['cc'] = ", ".join([cc])
msg['To'] = recipient
rcpt = bcc.split(",") +cc.split(",") + [recipient]
message = """
<html>
<body>
Good morning, <br> <br>
"""+message_records+"""<br> <br>
Thank you and have a wonderful day!
</body>
</html>
"""
if attach==1:
msg.attach(MIMEText(message,'html'))
filename = "ASN-" + str(date.today())+'.csv'
attachment = MIMEApplication(df.to_csv(index=False))
attachment["Content-Disposition"] = 'attachment; filename=" {}"'.format(filename)
msg.attach(attachment)
else:
msg.attach(MIMEText(message,'html'))
server.sendmail(sender, rcpt, msg.as_string())
server.close()```
I suggest you look at the SENDGRID library for python. It uses the API key that you get from the service and it is built just for this service.
https://docs.sendgrid.com/for-developers/sending-email/v3-python-code-example
See if this code produces the same duplicate issue you are seeing.
If I remember right, send grid keeps track of the sent mail messages. Make sure the "to - recipient" list does not have duplicate addresses.
I do not see any obvious issues with the above code.
Here is the PyPi link. There are a ton of examples on usage.
https://pypi.org/project/sendgrid/
Im trying to send gmail email using python. The email includes plain text and an html image to be shown in the email. However when i try sending the email, the text is not showing (only image is shown).
Below is the code:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
host='smtp.gmail.com'
port=587
username='sender#gmail.com'
password='mypassword'
from_email=username
to_list=['recipient#gmail.com']
email_conn=smtplib.SMTP(host,port)
email_conn.ehlo()
email_conn.starttls()
email_conn.login(username,password)
msg=MIMEMultipart('Alternative')
temp=MIMEMultipart('Alternative2')
msg['Subject']='Hello'
msg['From']=username
txt='Welcome home'
part1=MIMEText(txt,'plain')
msgText = MIMEText('<img src="cid:image1">', 'html')
temp.attach(msgText)
fp = open('/home/user/Pictures/image.jpg', 'rb')
msgImage = MIMEImage(fp.read())
fp.close()
# Define the image's ID as referenced above
msgImage.add_header('Content-ID', '<image1>')
temp.attach(msgImage)
msg.attach(part1)
msg.attach(temp)
email_conn.sendmail(from_email,to_list,msg.as_string())
email_conn.quit()
The immediate error is that you are creating a invalid MIME part with type multipart/Alternative2. You seem to be confusing the type (which should be one out of a limited set of IANA-approved labels) with a unique identifier.
More fundamentally, you seem to be following some obsolete email guideline. The proper way to create a new message in Python 3.6+ is to use the (no longer very) new EmailMessage API.
Also, you will want to restructure your code so that the message creation is not mixed with the message sending. In the following, I have simply removed all the smtplib code; this also makes it easy for you to troubleshoot locally with print(msg.as_string()) instead of sending the message.
from email.message import EmailMessage
from email.utils import make_msgid
username = 'sender#gmail.com'
to_list = ['recipient#gmail.com']
msg = EmailMessage()
msg['Subject'] = 'Hello'
msg['From'] = username
# Need recipient!
msg['To'] = ', '.join(to_list)
msg.set_content('Welcome home')
image_id = make_msgid()
# Notice closing slash at the end of <img ... />
msg.add_alternative('<img src="%s" />' % image_id.strip('<>'), subtype='html')
with open('/home/user/Pictures/image.jpg', 'rb') as fp:
msg.get_payload()[1].add_related(
fp.read(), 'image', 'jpeg', cid=image_id)
This rather closely follows the "asparagus" example from the email examples in the documentation.
You would then go on to create an SMTP session and smtp.send_message(msg) rather than take the detour to separately and explicitly convert the message to a string you can pass to the legacy sendmail method; this is one of the many improvements in the new API.
trying to send email through python. Can get it to send email with correct text content in the body but it's printing the the actual variable name "New Companies" instead of it's content. here's the code and the resulting email.
(not sure why the html tags aren't showing up in my code below, but I used html and body tags before and after the email content)
Any and all help is appreciated.
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
EMAIL_SERVER = 'blahblah'
EMAIL_PORT = 25
f = open('diff.txt', 'r')
NEW_COMPANIES = f.read()
EMAIL_FROM = 'blabal'
RECIPIENT_LIST = ['blahblah']
msg = MIMEMultipart()
msg['From'] = EMAIL_FROM
msg['To'] = ", ".join(RECIPIENT_LIST)
msg['Subject'] = 'North Carolina New Business Registration'
body = '''<html>
<body>
New Business Names:<br><br>
body.format('NEW_COMPANIES')
<br><br>
Affiliate: r2thek
<br><br>
Website Link:
https://www.sosnc.gov/online_services/search/by_title/_Business_Registration
</body>
</html>'''
body.format('NEW_COMPANIES')
msg.attach(MIMEText(body, 'html'))
smtpserver = smtplib.SMTP(EMAIL_SERVER, EMAIL_PORT)
smtpserver.sendmail(EMAIL_FROM, RECIPIENT_LIST, msg.as_string())
smtpserver.quit()
Email Result:
New Business Names:
{NEW_COMPANIES}
Affiliate: r2thek
Website Link: https://www.sosnc.gov/online_services/search/by_title/_Business_Registration
It doesn't look like you've passed any variables to format the string, you'll need to do
body.format(variable1, variable2, etc)
In your case I think it's just the one variable, so wherever you stored what NEW_COMPANIES should be needs to be used as the argument for str.format()
In addition to this thread send outlook mail via win32com, i'd like to know if there is a possibility to use mail.From alike method. When you create an email, you can choose from what email you'd like to send it.
And for the future, where could i get this information from? I mean do those commands work with COM object of outlook application?
Here's a code which I have been using for long time and hopefully will work for you as well,
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
def sendMail(to, subject, text):
assert type(to)==list
fro = "abc#xyz.com" # use your from email here
msg = MIMEMultipart()
msg['From'] = fro
msg['To'] = COMMASPACE.join(to)
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = subject
msg.attach(MIMEText(html, 'html'))
smtp = smtplib.SMTP('mailhost.abcd.co.in') #use your mailhost here, it's dummy.
smtp.sendmail("", to, msg.as_string() )
smtp.close()
TOADDR = ['abc#xyz.com'] # list of emails address to be sent to
html = """\
<html>
<head></head>
<body>
<p>Hi!<br>
How are you?<br>
Here is the link you wanted.
</p>
</body>
</html>
"""
sendMail( TOADDR, "hello",html)
I've written a python script to send out emails, but now I'm wondering if it's possible to send emails to Microsoft exchange groups using python? I've tried including the group in the cc and to fields but that doesn't seem to do the trick. It shows up, but doesn't seem to correspond to a group of emails; it's just plain text.
Anyone know if this is possible?
This is definitely possible. Your exchange server should recognize it if you treat it as a full address. For example if you want to send it to person1, person2, and group3, use the following:
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
address_book = ['person1#company.com', 'person2#company.com', 'group3#company.com']
msg = MIMEMultipart()
sender = 'me#company.com'
subject = "My subject"
body = "This is my email body"
msg['From'] = sender
msg['To'] = ','.join(address_book)
msg['Subject'] = subject
msg.attach(MIMEText(body, 'plain'))
text=msg.as_string()
#print text
# Send the message via our SMTP server
s = smtplib.SMTP('our.exchangeserver.com')
s.sendmail(sender,address_book, text)
s.quit()