Skip to content

Instantly share code, notes, and snippets.

@yeiichi
Last active July 7, 2024 08:58
Show Gist options
  • Save yeiichi/aca002d51cb326322f399f3b5731761e to your computer and use it in GitHub Desktop.
Save yeiichi/aca002d51cb326322f399f3b5731761e to your computer and use it in GitHub Desktop.
Load message from an EML file and send it to an SMTP server.
#!/usr/bin/env python3
import email
import email.utils
import smtplib
def load_eml(src_eml):
"""Load message from an EML file.
Returns:
_msg (email.message.Message): Message from an EML file.
References:
Parse an eml file
https://docs.python.org/3/library/email.parser.html#email.message_from_bytes
Prefer `message_from_bytes()` to `email.message_from_string()`
https://stackoverflow.com/a/19508543/11042987
"""
with open(src_eml, 'rb') as f:
_msg = email.message_from_bytes(f.read()) # Prefer 'bytes' to 'string'
# Update the dttm
dttm = email.utils.format_datetime(email.utils.localtime())
_msg.replace_header('date', dttm)
return _msg
def send_message(msg_in):
"""Send a msg object to an SMTP server.
Args:
msg_in (email.message.Message):
"""
_host = 'mail.example.com'
_user = 'yourname@example.com'
_pass = '<PASSWORD>'
with smtplib.SMTP_SSL(_host, 465) as s:
s.login(_user, _pass)
s.send_message(msg_in)
print('\033[93mEmail sent!\033[0m')
def main():
"""Load message from an EML file and send it to an SMTP server.
"""
source_eml = 'source.eml'
msg = load_eml(source_eml)
send_message(msg)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment