Unable to send html file content as email body in python - python

I have a html file whose contents I want to send in the email body using python. Below is the python script:
import smtplib,email,email.encoders,email.mime.text,email.mime.base
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email import encoders
from email.message import Message
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
import codecs
msg = MIMEMultipart()
# me == my email address
# you == recipient's email address
me = "a#b.com"
you = "b#a.com"
# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('mixed')
msg['Subject'] = "Automation Testing"
msg['From'] = me
msg['To'] = you
# Create the body of the message (a plain-text and an HTML version).
f = codecs.open('/Users/test.htm')
html = f.read()
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(part2)
composed = msg.as_string()
fp = open('msgtest.txt', 'w')
fp.write(composed)
# Credentials (if needed)
# The actual mail send
server = smtplib.SMTP('smtp.a.com', 25)
server.starttls()
server.sendmail(me, you, composed)
server.quit()
fp.close()
But, it is sending only an empty email with no html content in the body. Please tell me how to fix this.

Related

Send video file via mail python

I'm trying to send example.mp4 file with mail in below codes. Mail send successfully. But when I download the video in related mail. Video is not working after download from mail. But normally video is working successfully.Where is my fault ?
import smtplib
from email import message, encoders
from email.message import EmailMessage
from email.mime.base import MIMEBase
from os.path import basename
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from_addr = 'FROM_MAIL'
to_addr = 'TO_ADDRESS'
subject = 'I just sent this email from Python!'
content = 'Test'
# Initializing video object
video_file = MIMEBase('application', "octet-stream")
# Importing video file
video_file.set_payload(open('example.mp4', "rb").read())
# Encoding video for attaching to the email
encoders.encode_base64(video_file)
# creating EmailMessage object
msg = MIMEMultipart()
# Loading message information ---------------------------------------------
msg['From'] = "person_sending#gmail.com"
msg['To'] = "person_receiving#gmail.com"
msg['Subject'] = 'text for the subject line'
msg.set_content('text that will be in the email body.')
msg.add_attachment(video_file, filename="example.mp4")
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.login(from_addr, 'APP_PASS')
server.send_message(msg, from_addr=from_addr, to_addrs=[to_addr])
Adding this did it for me:
video_file.add_header('Content-Disposition',
'attachment; filename={}'.format("test.mp4"))

Receiving - SMTP instance has no attribute error

I am trying to automate sending emails to a list of clients using a python script. It worked perfectly before they made it so you can't use the less secure app on 30th May 2022. I added the 2FA password and approved my computer. I am now receiving the error
server.send_message(message)
AttributeError: SMTP instance has no attribute 'send_message' when I try to run my code. Any ideas on how to fix this? I will attach the code below and have of course taken out sensitive information.
Python Code
MY_ADDRESS = "****#gmail.com" # Email Address
MY_PASSWORD = "****Password****" # Emails 2FA Pass
RECIPIENT_ADDRESS = ['****#gmail.com', '****#gmail.com'] # Recipient Address
HOST_ADDRESS = 'smtp.gmail.com'
HOST_PORT = 587
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.mime.text import MIMEText
# Connection with the server
server = smtplib.SMTP(host=HOST_ADDRESS, port=HOST_PORT)
server.starttls()
server.login(MY_ADDRESS, MY_PASSWORD)
# Creation of the MIMEMultipart Object
message = MIMEMultipart()
# Setup of MIMEMultipart Object Header
message['From'] = MY_ADDRESS
message['To'] = ", ".join(RECIPIENT_ADDRESS)
message['Subject'] = "Test Email - July"
# Creation of a MIMEText Part
textPart = MIMEText("Hello **** & ****,\n\nAttached below is your test bill for the month of July 2022. \n\nBest,\Your Management", 'plain')
# Creation of a MIMEApplication Part
filename = "Test Bill - Billy.pdf"
filePart = MIMEApplication(open(filename,"rb").read(),Name=filename)
filePart["Content-Disposition"] = 'attachment; filename="%s' % filename
# Parts attachment
message.attach(textPart)
message.attach(filePart)
# Send Email and close connection
server.send_message(message)
server.quit()
Try the following code:
import smtplib
from email.utils import formataddr
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
msg = MIMEMultipart()
body_part = MIMEText('Write you text here.')
user = 'xxxx#gmail.com'
password = 'xxxx'
msg['Subject'] = 'You subject'
msg['From'] = formataddr(('yyyyy', 'xxxx#gmail.com'))
msg['To'] = 'yyyy#gmail.com'
msg.attach(body_part)
smtp_obj = smtplib.SMTP_SSL("smtp.gmail.com", 465)
smtp_obj.login(user, password)
smtp_obj.sendmail(msg['From'], msg['To'], msg.as_string())
smtp_obj.quit()
Update: How to attach a file to your email:
Just add the following lines to the script above.
from email.mime.application import MIMEApplication
path = './../' #The path of your file.
with open(path + filename,'rb') as file:
msg.attach(MIMEApplication(file.read(), Name='filename'))

python MIME attaching multiple attachments to a multipart message

I am trying to attach multiple attachments to a email.mime.multipart object:
from smtplib import SMTP
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
message = MIMEMultipart('alternative')
message['Subject'] = 'test'
for i in range(10):
title="<h2>{}</h2>".format(i)
message.attach(MIMEText(title,"html",_charset="utf-8"))
Here I can check that the payload contains the 10 elements:
message.get_payload()
I can see the list of 10 elements, which seems correct.
However when I send the email with the following code:
MAIL_HOST = 'smtp.gmail.com:587'
MAIL_USER = 'xxx#gmail.com'
MAIL_PASSWORD = 'xxx'
MAIL_REPICIENTS = ['xxx#gmail.com']
smtp = SMTP(MAIL_HOST)
smtp.ehlo()
smtp.starttls()
smtp.login(MAIL_USER, MAIL_PASSWORD)
smtp.sendmail(MAIL_USER, MAIL_REPICIENTS, message.as_string())
smtp.close()
The email contains only the last element of the list.
Can anyone help me with that?
That’s because you are attaching 10 different messages. Why you want is to attach one message. Change your code to this:
from smtplib import SMTP
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
message = MIMEMultipart('alternative')
message['Subject'] = 'test'
html = ''
for i in range(10):
title="<h2>{}</h2>".format(i)
html += title
message.attach(MIMEText(html,"html",_charset="utf-8"))

Sending attachment in HTML email with Python

I saw there are a few somewhat similar questions on stack overflow already, but I couldn't find a solution to my specific problem in them.
I am trying to use Python to send an HTML email with a .pdf attachment. It seems to work fine when I check my email on gmail.com, but when I check the message through apple's Mail program, I do not see the attachment. Any idea what is causing this?
My code is below. A lot of it is copied from various places on stack overflow, so I do not completely understand what each part is doing, but it seems to (mostly) work:
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
#plain text version
text = "This is the plain text version."
#html body
html = """<html><p>This is some HTML</p></html>"""
# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = "Deliverability Report"
msg['From'] = "me#gmail.com"
msg['To'] = "you#gmail.com"
# Record the MIME types of both parts - text/plain and text/html
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
# create PDF attachment
filename='graph.pdf'
fp=open(filename,'rb')
att = email.mime.application.MIMEApplication(fp.read(),_subtype="pdf")
fp.close()
att.add_header('Content-Disposition','attachment',filename=filename)
# Attach parts into message container.
msg.attach(att)
msg.attach(part1)
msg.attach(part2)
# Send the message via local SMTP server.
s = smtplib.SMTP()
s.connect('smtp.webfaction.com')
s.login('NAME','PASSWORD')
s.sendmail(msg['From'], msg['To'], msg.as_string())
s.quit()
I'm not sure if it is relevant, but I am running this code on a WebFaction server.
Thanks for the help!
To have text, html and attachments at the same time it is necessary to use both mixed and alternative parts.
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
text = "This is the plain text version."
html = "<html><p>This is some HTML</p></html>"
text_part = MIMEText(text, 'plain')
html_part = MIMEText(html, 'html')
msg_alternative = MIMEMultipart('alternative')
msg_alternative.attach(text_part)
msg_alternative.attach(html_part)
filename='graph.pdf'
fp=open(filename,'rb')
attachment = email.mime.application.MIMEApplication(fp.read(),_subtype="pdf")
fp.close()
attachment.add_header('Content-Disposition', 'attachment', filename=filename)
msg_mixed = MIMEMultipart('mixed')
msg_mixed.attach(msg_alternative)
msg_mixed.attach(attachment)
msg_mixed['From'] = 'me#gmail.com'
msg_mixed['To'] = 'you#gmail.com'
msg_mixed['Subject'] = 'Deliverability Report'
smtp_obj = smtplib.SMTP('SERVER', port=25)
smtp_obj.ehlo()
smtp_obj.login('NAME', 'PASSWORD')
smtp_obj.sendmail(msg_mixed['From'], msg_mixed['To'], msg_mixed.as_string())
smtp_obj.quit()
Message structure should be like this:
Mixed:
Alternative:
Text
HTML
Attachment
Use
msg = MIMEMultipart('mixed')
instead of 'alternative'

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

Categories