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"))
To automate a task I need to get a code sent to me by e-mail in my outlook in order to log into a website. I am new to python, so I was wondering, how can I do it using the win32com module.
Thanks.
You could use smtplib and email.MIME libreries:
This is an example to how send an email from/to a outlook email:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
strFrom = 'email#hotmail.com'
strTo = 'email#hotmail.com'
msgRoot = MIMEMultipart('related')
msgRoot['Subject'] = 'Email subject'
msgRoot['From'] = strFrom
msgRoot['To'] = strTo
msgAlternative = MIMEMultipart('alternative')
msgRoot.attach(msgAlternative)
body='text, can be plain or html'
msgText_Total=MIMEText(body,'html')
msgAlternative.attach(msgText_Total)
s = smtplib.SMTP('SMTP.Office365.com:587')
s.ehlo()
s.starttls()
s.login('email#hotmail.com','password')
s.sendmail(strFrom, msgRoot["To"].split(","), msgRoot.as_string())
s.quit()
I hope this will helpful for you.
Hi I'm trying to use SMTP in python 3 to send an email, but with a different email address that I have authenticated. Is there a way I can do this? Below is my sample code. I know that there are some source working with gmail account, but couldn't find any for normal email.
import smtplib
import datetime
from email.message import EmailMessage
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from dateutil.relativedelta import relativedelta
dateToday = datetime.date.today()
#Create a multipart for attachment
msg = MIMEMultipart()
msg['From'] = 'example2#example.com'
msg['To'] = 'example#example.com'
msg['Subject'] = 'Test'
msg.attach(MIMEText('This is a test message'))
part = MIMEBase('application','octet-stream')
#Open a file for attachment
part.set_payload(open("Workbook1.xlsx",'rb').read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="Workbook1 (' + str(dateToday) + ').xlsx"')
msg.attach(part)
#Create user name and password for authentication
username = 'example1#example.com'
password = '1234'
smtp = smtplib.SMTP('mail.example.com', 11)
smtp.starttls()
smtp.login(username, password)
smtp.sendmail(msg['From'], msg['To'], msg.as_string())
print('Email successfully sent to: ' + msg['To'])
smtp.quit()
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"))
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