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"))
Related
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'))
I am sending an email with excel file as an attachment.
Everything is fine, but when I try to open excel file from email, I got an error:
I am not very familiar with python, what can be the problem here?
Code below:
import pandas as pd
import numpy as np
import pyodbc
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
fromaddr = "FromEmail"
toaddr = "ToEmail"
# instance of MIMEMultipart
msg = MIMEMultipart()
# storing the senders email address
msg['From'] = fromaddr
# storing the receivers email address
msg['To'] = toaddr
# storing the subject
msg['Subject'] = "Sending Attachement"
# string to store the body of the mail
body = "Hello, this is a test email!"
# attach the body with the msg instance
msg.attach(MIMEText(body, 'plain'))
# open the file to be sent
filename = "AZ.xlsx"
attachment = open('C:\\Users\\Folder\\AZ.xlsx',encoding='utf-8',errors='ignore')
# instance of MIMEBase and named as p
p = MIMEBase('application', 'octet-stream')
# To change the payload into encoded form
p.set_payload((attachment).read())
# encode into base64
encoders.encode_base64(p)
p.add_header('Content-Disposition', "attachment; filename= %s" % filename)
# attach the instance 'p' to instance 'msg'
msg.attach(p)
# creates SMTP session
s = smtplib.SMTP('10.10.10.10: 25')
# start TLS for security
s.starttls()
# Authentication
#s.login(fromaddr, "password")
# Converts the Multipart msg into a string
text = msg.as_string()
# sending the mail
s.sendmail(fromaddr, toaddr, text)
# terminating the session
s.quit()
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.
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
I have a text file to be sent via e-mail. I used the following code to send e-mail through smtplib. This code prints the attachment as e-mail body. Since my text file is bit larger all the content is not visible in mail body? How to display all the content in e-mail body? Any suggestions?
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
msg = MIMEMultipart()
msg['Subject'] = 'ANALYSIS REPORT'
filename = "report.txt"
f = file(filename)
attachment = MIMEText(f.read())
msg.attach(attachment)
smtpObj = smtplib.SMTP('mail.my-domain.com', 25)
smtpObj.sendmail(sender, receivers, msg.as_string())
print "e-mail Successfully Sent!"
I would try to compress the content body, maybe that would get the message size down enough to get the mail through.
Example:
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.mime.application import MIMEApplication
from email.MIMEImage import MIMEImage
import io
import gzip
msg = MIMEMultipart()
msg['Subject'] = 'ANALYSIS REPORT'
msg.attach(MIMEText('report attached'))
filename = "report.txt"
with open(filename, 'rb') as f, io.BytesIO() as b:
g = gzip.GzipFile(mode='wb', fileobj=b)
g.writelines(f)
g.close()
attachment = MIMEApplication(b.getvalue(), 'x-gzip')
attachment['Content-Disposition'] = 'attachment; filename=report.txt.gz'
msg.attach(attachment)
smtpObj = smtplib.SMTP('mail.my-domain.com', 25)
print smtpObj.sendmail(sender, receivers, msg.as_string())
print "e-mail Successfully Sent!"