Skip to content

Instantly share code, notes, and snippets.

@sourceperl
Created May 12, 2023 16:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sourceperl/65f29d9074d0eda929aab35a94c8222c to your computer and use it in GitHub Desktop.
Save sourceperl/65f29d9074d0eda929aab35a94c8222c to your computer and use it in GitHub Desktop.
Send an mail to smtp.free.fr server
#!/usr/bin/env python3
""" Send mail with SMTP protocol. """
import logging
import re
import smtplib
from typing import List, Union
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
from private_data import SMTP_USER, SMTP_PASS, SMTP_FROM
# some function
def is_html(text: str) -> bool:
"""Check if text contain HTML code."""
pattern = re.compile(r'<\w*?>')
return pattern.search(text) is not None
def send_mail(address: Union[str, List], subject: str = '', body: str = '', attachments: list = None):
"""Send an email with SMTP SSL."""
# params
addr_l = []
if isinstance(address, str):
addr_l.append(address)
elif isinstance(address, (list, tuple)):
addr_l = list(address)
if attachments is None:
attachments = []
# connect and login
smtp = smtplib.SMTP_SSL(host='smtp.free.fr', port=465)
smtp.login(SMTP_USER, SMTP_PASS)
# format mail
msg = MIMEMultipart()
msg['Subject'] = subject
msg['From'] = SMTP_FROM
msg['To'] = ', '.join(addr_l)
# add body (auto-detect html type)
msg.attach(MIMEText(body, 'html' if is_html(body) else 'plain'))
# add attachments
for filename, content in attachments:
part = MIMEBase('application', 'octet-stream')
part.set_payload(content)
encoders.encode_base64(part)
part.add_header('Content-Disposition', f'attachment; filename={filename}')
msg.attach(part)
# send
send_status = smtp.sendmail(SMTP_FROM, address, msg.as_string())
logging.debug(f'SMTP status: {send_status}')
smtp.quit()
if __name__ == '__main__':
# logging setup
logging.basicConfig(format='%(asctime)s %(message)s', level=logging.DEBUG)
# send mail
logging.debug('send mail')
send_mail(['me@example.com', ], subject='My file', body='See file attached.',
attachments=[('readme.txt', b'my text')])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment