-
Notifications
You must be signed in to change notification settings - Fork 0
/
SendGmail.py
executable file
·58 lines (49 loc) · 1.99 KB
/
SendGmail.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
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
class SendGmail:
def __init__(self, user, password):
self.user = user
self.password = password
def send(self, recipient, subject, text, *attachmentPaths):
msg = MIMEMultipart()
msg['From'] = self.user
msg['To'] = recipient
msg['Subject'] = subject
msg.attach(MIMEText(text))
for attachmentPath in attachmentPaths:
msg.attach(self.getAttachment(attachmentPath))
mailServer = smtplib.SMTP('smtp.gmail.com', 587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(self.user, self.password)
mailServer.sendmail(self.user, recipient, msg.as_string())
mailServer.close()
def getAttachment(self, attachmentFilePath):
contentType, encoding = mimetypes.guess_type(attachmentFilePath)
if contentType is None or encoding is 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