python实现的使用gmail发邮件的代码段

找到个用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_base64

10 

11 def sendMail(subject, text, *attachmentFilePaths):

12   gmailUser = '[email protected]'

13   gmailPassword = 'yourpasswd'

14   recipient = '[email protected];[email protected]'

15 

16   msg = MIMEMultipart()

17   msg['From'] = gmailUser

18   msg['To'] = recipient

19   msg['Subject'] = subject

20   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

你可能感兴趣的:(python)