The implementation code of Gmail email in python

Source: Internet
Author: User
Tags in python
The code is as follows Copy Code
View Code
Import OS
Import Smtplib
Import Mimetypes
From email. Mimemultipart Import Mimemultipart
From email. Mimebase Import Mimebase
From email. Mimetext Import Mimetext
From email. Mimeaudio Import Mimeaudio
From email. Mimeimage Import Mimeimage
From email. Encoders Import Encode_base64

def sendMail (subject, Text, *attachmentfilepaths):
Gmailuser = Count@gmail.com ' "> ' youraccount@gmail.com '
Gmailpassword = ' yourpasswd '
Recipient = ' mail1@gmail.com;mail2@gmail.com '

msg = Mimemultipart ()
Msg[' from '] = Gmailuser
Msg[' to '] = Recipient
msg[' Subject '] = Subject
Msg.attach (Mimetext (text))

For Attachmentfilepath in Attachmentfilepaths:
Msg.attach (GetAttachment (Attachmentfilepath))

MailServer = Smtplib. SMTP (' smtp.gmail.com ', 587)
Mailserver.ehlo ()
Mailserver.starttls ()
Mailserver.ehlo ()
Mailserver.login (Gmailuser, Gmailpassword)
Mailserver.sendmail (Gmailuser, Recipient, msg.as_string ())
Mailserver.close ()

Print (' Sent email to%s '% recipient)

def getattachment (Attachmentfilepath):
ContentType, encoding = Mimetypes.guess_type (Attachmentfilepath)

If ContentType is none or encoding are not none:
ContentType = ' Application/octet-stream '

MainType, subtype = contenttype.split ('/', 1)
File = open (Attachmentfilepath, ' RB ')

if MainType = = ' Text ':
Attachment = Mimetext (File.read ())
elif MainType = = ' message ':
Attachment = email.message_from_file (file)
elif MainType = = ' Image ':
Attachment = Mimeimage (File.read (), _subtype=subtype)
elif MainType = = ' Audio ':
Attachment = Mimeaudio (File.read (), _subtype=subtype)
Else
Attachment = Mimebase (MainType, subtype)
Attachment.set_payload (File.read ())
Encode_base64 (Attachment)

File.close ()

Attachment.add_header (' content-disposition ', ' attachment ', Filename=os.path.basename (AttachmentFilePath))
Return attachment
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.