Skip to content

Instantly share code, notes, and snippets.

@Raudcu
Last active May 11, 2021 13:48
Show Gist options
  • Save Raudcu/3697c4555ec2602cc44216a1f32b8382 to your computer and use it in GitHub Desktop.
Save Raudcu/3697c4555ec2602cc44216a1f32b8382 to your computer and use it in GitHub Desktop.
Python script to send mails with append
import argparse
import smtplib
from email.message import EmailMessage
import mimetypes
# Parser
parser = argparse.ArgumentParser(description="Send files through mail")
parser.add_argument("files", metavar="FILES", nargs="+", help="Files to send")
parser.add_argument(
"-r",
"--recipient",
required=False,
action="append",
metavar="RECIPIENT",
default=["me"],
dest="recipients",
help="A To: header value",
)
args = parser.parse_args()
# Recipients
rcp = {
"me": "asd@asd.com",
"someone_else": "asdasd@asd.com"
}
recipients = [rcp[person] for person in args.recipients]
# Construyo el mail
email = EmailMessage()
email["from"] = "from@asd.com"
email["to"] = ", ".join(recipients)
email["subject"] = " ".join(args.files)
# Append the files
for filename in args.files:
# Guess the content type based on the file's extension.
# If no guess could be made, or the file is encoded (compressed),
# so use a generic bag-of-bits type.
ctype, encoding = mimetypes.guess_type(filename)
if ctype is None or encoding is not None:
ctype = "application/octet-stream"
maintype, subtype = ctype.split("/", 1)
with open(filename, "rb") as fp:
email.add_attachment(
fp.read(), maintype=maintype, subtype=subtype, filename=filename
)
# Send
with smtplib.SMTP(host="AAAAA", port=587) as smtp:
smtp.starttls()
smtp.login("AAAAA", "AAAAA")
smtp.send_message(email)
print("Sent!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment