Skip to content
This repository was archived by the owner on Jan 31, 2025. It is now read-only.
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions mail/mail.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ def __init__(self, prot, *argv):
def login(self, account, passwd):
self.__prot.login(account, passwd)

def send(self, frm, to, subject, content):
self.__prot.send(frm, to, subject, content)
def send(self, frm, to, subject, content, attachments=None):
self.__prot.send(frm, to, subject, content, attachments)

def quit(self):
self.__prot.quit()
43 changes: 40 additions & 3 deletions mail/prot/smtp.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
import smtplib
import os
import sys
from email import encoders
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from datetime import date


class Smtp:
Expand All @@ -19,9 +26,39 @@ def default_setup(self):
def login(self, account, passwd):
self.__smtp_obj.login(account, passwd)

def send(self, frm, to, subject, content):
self.__smtp_obj.sendmail(
frm, to, 'Subject:' + subject + '\n' + content)
def send(self, frm, to, subject, content, attachments):
'''
@frm str
@to list of email. e.g. ['[email protected]', '[email protected]']
@subject str
@content str
@attachments None or list of file path. e.g. ['filePath1', 'filePath2']
'''
msg = MIMEMultipart()
msg['From'] = frm
msg['To'] = ', '.join(to)
msg['Subject'] = subject
msg['Date'] = str(date.today())
msg.attach(MIMEText(content))

for filePath in attachments:
try:
with open(filePath, 'rb') as fp:
file = MIMEBase('application', 'octet-stream')
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you explain why you put the hardcode here?

file.set_payload(fp.read())

encoders.encode_base64(file)
file.add_header('Content-Disposition', 'attachment',
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ditto.

filename=os.path.basename(filePath))
msg.attach(file)
except:
print('Unable to open one of attachments. Error: ', sys.exc_info()[0])

try:
self.__smtp_obj.sendmail(frm, to, msg.as_string())
print('Send email with attachment success.')
except expression as identifier:
print('Send with attatchment Error: ', sys.exc_info()[0])

def quit(self):
self.__smtp_obj.quit()