To send an email, I use a certain function:
def send_email(self, subject, to_addr, from_addr, content):
body_text = ''
for cnt in content:
body_text += str(cnt)
BODY = '\r\n'.join((
'From: %s' % from_addr,
'To: %s' % to_addr,
'Subject: %s' % subject,'', body_text
))
server = smtplib.SMTP(self.host)
server.sendmail(from_addr, to_addr, BODY.encode('utf-8'))
server.quit()
As you can see, the message body is in the body_text
variable.
The message is generated in this piece of code:
class Event():
def __init__(self, path):
self.path = path
self.time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
def __str__(self):
return ('Time: ' + self.time + '\tPath: '+ '"' + self.path + '"' + '\n')
Could you tell me please, how can I format a message sent by mail?
I would like that it was possible to make the text bold, italic or underlined, insert a hyperlink and, accordingly, all this would be displayed correctly in the letter itself.
Now if I use the class color
in the function where the text is formed:
class color:
PURPLE = '\033[95m'
CYAN = '\033[96m'
DARKCYAN = '\033[36m'
BLUE = '\033[94m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
END = '\033[0m'
def __str__(self):
return (color.BOLD + 'Time: ' + color.END + self.time + '\tPath: '+ '"' + self.path + '"' + '\n')
then the following characters will be displayed in the incoming message:
After changes, if you do print(message_str)
:
In general, it turned out, here is my code:
def send_email(self, subject, to_addr, from_addr, content):
msg = MIMEMultipart()
msg['From'] = from_addr
msg['To'] = to_addr
msg['Subject'] = subject
body_html = '<html><body>'
for cnt in content:
body_html += ('<html><head></head><body><p><b>Time: </b>' + '<em>' + str(cnt.getTime()) + '</em>'
+ '<br><b>Path: </b>' +
'<a href='+'"'+ str(cnt.getPath()) + '">' + str(cnt.getPath()) + ''</a></body></html>'')
part_msg = MIMEText(body_html, 'html')
msg.attach(part_msg)
server = smtplib.SMTP(self.host)
server.sendmail(from_addr, to_addr, msg.as_string())
server.quit()