Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I had created an Outlook template. Now I have to send that mail to many users. want to prepare a script that will fetch the CSV file which includes emails list and send it to them.
Outlook Template contains Coloured fonts and underlined text with multiple font sizes.
Use the smtplib that comes with python. Note that this will require your email account allows smtp, which is not necessarily enabled by default.
SERVER = "smtp.example.com"
FROM = "yourEmail#example.com"
TO = ["listOfEmails"] # must be a list
SUBJECT = "Subject"
TEXT = "Your Text"
# Prepare actual message
message = """From: %s\r\nTo: %s\r\nSubject: %s\r\n\
%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
# Send the mail
import smtplib
server = smtplib.SMTP(SERVER)
server.sendmail(FROM, TO, message)
server.quit()
EDIT: this example uses reserved domains like described in RFC2606
SERVER = "smtp.example.com"
FROM = "johnDoe#example.com"
TO = ["JaneDoe#example.com"] # must be a list
SUBJECT = "Hello!"
TEXT = "This is a test of emailing through smtp of example.com."
# Prepare actual message
message = """From: %s\r\nTo: %s\r\nSubject: %s\r\n\
%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
# Send the mail
import smtplib
server = smtplib.SMTP(SERVER)
server.login("MrDoe", "PASSWORD")
server.sendmail(FROM, TO, message)
server.quit()
Maybe take a look at the library yagmail.
From the top of the page:
import yagmail
yag = yagmail.SMTP()
contents = [
"This is the body, and here is just text http://somedomain/image.png",
"You can find an audio file attached.", '/local/path/to/song.mp3'
]
yag.send('to#someone.com', 'subject', contents)
# Alternatively, with a simple one-liner:
yagmail.SMTP('mygmailusername').send('to#someone.com', 'subject', contents)
When it comes to coloring and font changes - you'll have to use HTML for that. Define a body in a separate string and pass that into contents.
Related
Looking to create and send messages with multiple files attached. Per the online gmail api documentation, there is a function for building messages with an attachment but no documentation for howto use it to create a message with multiple attachments.
Can I use the gmail API to send messages with multiple attachments programmatically? How might one do this?
With this function, you can send to one or multiple recipient emails, and also you can attach zero, one or more files. Coding improvement recommendations are welcome, however the way it is now, it works.
Python v3.7
smtplib from https://github.com/python/cpython/blob/3.7/Lib/smtplib.py (download the code and create the smtplib.py on your project folder)
def send_email(se_from, se_pwd, se_to, se_subject, se_plain_text='', se_html_text='', se_attachments=[]):
""" Send an email with the specifications in parameters
The following youtube channel helped me a lot to build this function:
https://www.youtube.com/watch?v=JRCJ6RtE3xU
How to Send Emails Using Python - Plain Text, Adding Attachments, HTML Emails, and More
Corey Schafer youtube channel
Input:
se_from : email address that will send the email
se_pwd : password for authentication (uses SMTP.SSL for authentication)
se_to : destination email. For various emails, use ['email1#example.com', 'email2#example.com']
se_subject : email subject line
se_plain_text : body text in plain format, in case html is not supported
se_html_text : body text in html format
se_attachments : list of attachments. For various attachments, use ['path1\file1.ext1', 'path2\file2.ext2', 'path3\file3.ext3']. Follow your OS guidelines for directory paths. Empty list ([]) if no attachments
Returns
-------
se_error_code : returns True if email was successful (still need to incorporate exception handling routines)
"""
import smtplib
from email.message import EmailMessage
# Join email parts following smtp structure
msg = EmailMessage()
msg['From'] = se_from
msg['To'] = se_to
msg['Subject'] = se_subject
msg.set_content(se_plain_text)
# Adds the html text only if there is one
if se_html_text != '':
msg.add_alternative("""{}""".format(se_html_text), subtype='html')
# Checks if there are files to be sent in the email
if len(se_attachments) > 0:
# Goes through every file in files list
for file in se_attachments:
with open(file, 'rb') as f:
file_data = f.read()
file_name = f.name
# Attaches the file to the message. Leaves google to detect the application to open it
msg.add_attachment(file_data, maintype='application', subtype='octet-stream', filename=file_name)
# Sends the email that has been built
with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
smtp.login(se_from, se_pwd)
smtp.send_message(msg)
return True
Don't forget to activate less secure apps on your google account (https://myaccount.google.com/lesssecureapps) for this code to work.
Hope this helps
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I'm looking for a way to insert an html table into emails body (not attached / not hyperlinked).
What i did so far, and it is not good enough is:
1: Attach the table as a file to mail.
2: Convert html to csv and paste to email body.
3: Added a hyperlink to mail with link to table.
Tried with Mailer and email.MIMEMultipart
I guess i am missing something, it seems so trivial.
Thanks
From Python email documentation - 18.1.11. email: Examples:
Here’s an example of how to create an HTML message with an alternative
plain text version:
#! /usr/bin/python
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# me == my email address
# you == recipient's email address
me = "my#email.com"
you = "your#email.com"
# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = "Link"
msg['From'] = me
msg['To'] = you
# Create the body of the message (a plain-text and an HTML version).
text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org"
html = """\
<html>
<head></head>
<body>
<p>Hi!<br>
How are you?<br>
Here is the link you wanted.
</p>
</body>
</html>
"""
# 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)
# Send the message via local SMTP server.
s = smtplib.SMTP('localhost')
# sendmail function takes 3 arguments: sender's address, recipient's address
# and message to send - here it is sent as one string.
s.sendmail(me, you, msg.as_string())
s.quit()
I'm using EmailMessage to send emails via Amazon SES in Django. I am currently having trouble inserting new lines in the message. "\n" does not seem to work
How do I go about doing this?
As an example, this is what I've tried:
subject= "Test email with newline"
message = "%s %s is testing an email with a newline. \nCheck out this link too: http://www.example.com" % (user.first_name, user.last_name)
from_string = "<support#example.com>"
email_message = EmailMessage(subject, message, from_string, [user.email])
email_message.send()
When I send this email I get:
Michael Smith is testing an email with a newline. Check out this link too:
http://www.example.com
However, I expected the email to be formatted like this:
Michael Smith is testing an email with a newline.
Check out this link too: http://www.example.com
You can use attach_alternative() and provide html - in your case <p> or <br> will do the trick.
or
from django.core.mail import EmailMessage
subject= "Test email with newline"
html_context = "%s %s is testing an email with a newline. <br>Check out this link too: http://www.example.com" % (user.first_name, user.last_name)
from_string = "<support#example.com>"
msg = EmailMessage(subject,
html_context,
from_string,
[user.email])
msg.content_subtype = "html"
msg.send()
The better use is case it try sending html message where you can send email as html. There you can format your msg like whatever you want
I am using my company's smtp server to send email using python's email module. When I do that my email html is not rendering correctly. This is what I got:
sender = 'abc#abc.com'
# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('multipart')
msg['Subject'] = "My Report"
msg['From'] = sender
msg['To'] = ", ".join(recipients)
# Create the body of the message using html in msg_body
h = unicode(msg_body).encode("utf-8", "ignore")
# Record the MIME type
part = MIMEText(h, 'html')
# Attach parts into message container.
msg.attach(part)
pngfiles = ['image.png']
for file in pngfiles:
# Open the files in binary mode.
fp = open(file, 'rb')
img = MIMEImage(fp.read())
fp.close()
msg.attach(img)
# Send the message via local SMTP server.
s = smtplib.SMTP('send.abc.com')
s.sendmail(msg.get("From"), recipients, msg.as_string())
s.quit()
What should I do differently ?
Just wanted to throw out there how easy it is to send emails with attachments using yagmail (full disclose: I'm the developer). My philosophy was to have to only once figure out how to deal with the MIME stuff, and then never look back.
You can use the following 3 lines to send your email:
import yagmail
yag = yagmail.SMTP(sender, your_password)
# assuming your undefined "msg_body" is just some message (string)
yag.send(recipients, 'My report', contents = [msg_body, '/local/path/to/image.png'])
You can do all kind of things with contents: if you have a list of stuff it will nicely combine it. For example, a list of filenames will make it so that it will attach all. Mix it with some message, and it will have a message.
Any string that is a valid file will be attached, other strings are just text.
It will nicely handle HTML code, images (inline), text and any other files. And yes, I'm quite proud of it.
I encourage you to read the github documentation to see other nice features, for example you do not have to have your password / username in the script (extra safety) by using the keyring. Set it up once, and you'll be happy....
Oh yea, to install, you can use:
pip install yagmail # python 2
pip3 install yagmail # python 3
I am sending an email to a gmail account using Python. This is the code I'm using
msg = email.mime.multipart.MIMEMultipart()
msg['From'] = 'myemail#gmail.com'
msg['To'] = 'toemail#gmail.com'
msg['Subject'] = 'HTML test'
msg_html = email.mime.text.MIMEText('<html><head></head><body><b>This is HTML</b></body></html>', 'html')
msg_txt = email.mime.text.MIMEText('This is text','plain')
msg.attach(msg_html)
msg.attach(msg_txt)
#SNIP SMTP connection code
smtpConn.sendmail('myemail#gmail.com', 'toemail#gmail.com', msg.as_string())
When I view this email in gmail both the HTML and text version are shown like this:
This is HTML
This is text
It should be either displaying text or html, what causes this behavior.
The message is being sent as multipart/mixed (as this is the default) when it needs to be sent as multipart/alternative. mixed means that each part contains different content and all should be displayed, while alternative means that all parts have the same content in different formats and only one should be displayed.
msg = email.mime.multipart.MIMEMultipart("alternative")
Additionally, you should put the parts in increasing order of preference, i.e., text before HTML. The MUA (GMail in this case) will render the last part it knows how to display.
See the Wikipedia article on MIME for a good introduction to formatting MIME messages.