Adding HTML and multimedia content

In this section, we're going to see how we can send multimedia content as an attachment and how we can add HTML content. To do this, we'll use the Python email package.

First, we'll see how we can add HTML content. For that, create a script, add_html_content.py, and write the following content in it:

import os
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import getpass

host_name = 'smtp.gmail.com'
port = 465

sender = 'sender_emailid'
password = getpass.getpass()
receiver = 'receiver_emailid'

text = MIMEMultipart()
text['Subject'] = 'Test HTML Content'
text['From'] = sender
text['To'] = receiver

msg = """
<html>
<body>
<p>Hello there, <br>
Good day !!<br>
<a href="http://www.imdb.com">Home</a>
</p>
</body>
</html>
"""

html_content = MIMEText(msg, "html")
text.attach(html_content)
s = smtplib.SMTP_SSL(host_name, port)
print("Mail sent successfully !!")

s.login(sender, password)
s.sendmail(sender, receiver, text.as_string())
s.quit()

Run the script and you'll get the following output:

student@ubuntu:~/work/Chapter_11$ python3 add_html_content.py
Output:
Password:
Mail sent successfully !!

In the preceding example, we used the email package to send HTML content as a message through a Python script. We created a msg variable in which we stored HTML content.

Now, we'll see how we can add an attachment and send it through a Python script. For that, create a script, add_attachment.py, and write the following content in it:

import os
import smtplib
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
import getpass

host_name = 'smtp.gmail.com'
port = 465

sender = 'sender_emailid'
password = getpass.getpass()
receiver = 'receiver_emailid'

text = MIMEMultipart()
text['Subject'] = 'Test Attachment'
text['From'] = sender
text['To'] = receiver

txt = MIMEText('Sending a sample image.')
text.attach(txt)
f_path = 'path_of_file'
with open(f_path, 'rb') as f:
img = MIMEImage(f.read())
img.add_header('Content-Disposition',
'attachment',
filename=os.path.basename(f_path))

text.attach(img)
s = smtplib.SMTP_SSL(host_name, port)
print("Attachment sent successfully !!")
s.login(sender, password)
s.sendmail(sender, receiver, text.as_string())
s.quit()

Run the script and you'll get the output as follows:

student@ubuntu:~/work/Chapter_11$ python3 add_attachment.py
Output:
Password:
Attachment sent successfully !!

In the preceding example, we sent an image as an attachment to the receiver. We mentioned the sender's and receiver's email IDs. Next, in f_path, we mentioned the path of the image that we're sending as an attachment. Next, we send that image as an attachment to the receiver.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset