python實現的使用gmail發郵件的程式碼片段

來源:互聯網
上載者:User
找到個用python寫的使用gmail發郵件的代碼,挺好用的,當然錯誤處理都沒做,先記錄下來:View Code

 1 import os 2 import smtplib 3 import mimetypes 4 from email.MIMEMultipart import MIMEMultipart 5 from email.MIMEBase import MIMEBase 6 from email.MIMEText import MIMEText 7 from email.MIMEAudio import MIMEAudio 8 from email.MIMEImage import MIMEImage 9 from email.Encoders import encode_base6410 11 def sendMail(subject, text, *attachmentFilePaths):12   gmailUser = 'youraccount@gmail.com'13   gmailPassword = 'yourpasswd'14   recipient = 'mail1@gmail.com;mail2@gmail.com'15 16   msg = MIMEMultipart()17   msg['From'] = gmailUser18   msg['To'] = recipient19   msg['Subject'] = subject20   msg.attach(MIMEText(text))21 22   for attachmentFilePath in attachmentFilePaths:23     msg.attach(getAttachment(attachmentFilePath))24 25   mailServer = smtplib.SMTP('smtp.gmail.com', 587)26   mailServer.ehlo()27   mailServer.starttls()28   mailServer.ehlo()29   mailServer.login(gmailUser, gmailPassword)30   mailServer.sendmail(gmailUser, recipient, msg.as_string())31   mailServer.close()32 33   print('Sent email to %s' % recipient)34 35 def getAttachment(attachmentFilePath):36   contentType, encoding = mimetypes.guess_type(attachmentFilePath)37 38   if contentType is None or encoding is not None:39     contentType = 'application/octet-stream'40 41   mainType, subType = contentType.split('/', 1)42   file = open(attachmentFilePath, 'rb')43 44   if mainType == 'text':45     attachment = MIMEText(file.read())46   elif mainType == 'message':47     attachment = email.message_from_file(file)48   elif mainType == 'image':49     attachment = MIMEImage(file.read(),_subType=subType)50   elif mainType == 'audio':51     attachment = MIMEAudio(file.read(),_subType=subType)52   else:53     attachment = MIMEBase(mainType, subType)54   attachment.set_payload(file.read())55   encode_base64(attachment)56 57   file.close()58 59   attachment.add_header('Content-Disposition', 'attachment',   filename=os.path.basename(attachmentFilePath))60   return attachment
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.