Creating and sending an email with an attachment

Now, we will be sending an image attachment. This is a similar process to sending a plain text email. The only difference is that, here, we are using the MIMEImage class to create MIME message objects of image types. Follow these steps to get started:

  1. Create an SMTP object for the connection to the server
  2. Log in to your account
  3. Define the headers of your messages and login credentials
  4. Create a MIMEMultipart message object and attach the corresponding headers, that is, from, to, and subject
  5. Read and attach the image to the MIMEMultipart object message
  6. Finally, send the message

You can find the following code in the send_attachment_mail_from_gmail.py file:

from email.mime.multipart import MIMEMultipart
from email.MIMEImage import MIMEImage
from email.mime.text import MIMEText
import smtplib

# create message object instance
message = MIMEMultipart()

# setup the parameters of the message
message['From'] = "user@domain"
message['To'] = "user@domain"
message['Subject'] = "sending images as attachment"

# attach image to message body
message.attach(MIMEImage(file("image.jpg").read()))

In the previous code block we have created the message object instance and setup the parameters of the message,including attached image to message body. In the next code block we are going to create the connection with the smtp server, login with user credentials and send email with sendmail method.

# create server
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()

# Login Credentials for sending the mail
server.login(message['From'], "password")

# send the message via the server.
server.sendmail(message['From'], message['To'], message.as_string())
server.quit()
print("successfully sent email to %s:" % (message['To']))

In the previous example we have reviewed how to send an email with attached image using the Gmail SMTP server. You can test it changing the parameters of the message using your user and setting your password in the login() method credentials.

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

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