Difference between revisions of "Mail"
Jump to navigation
Jump to search
Line 20: | Line 20: | ||
def main(): | def main(): | ||
− | attachement1 = | + | attachement1 = filepath |
− | mailto = you@domain.tld | + | attachement2 = filepath |
+ | mailto = ['you@domain.tld'] | ||
+ | mailfrom = 'me@domain.tld' | ||
mailsubject = 'What this is about' | mailsubject = 'What this is about' | ||
mailtext = "Hi,\n\nI'd like to send you an email.\n\nBest Regards\n\nMe." | mailtext = "Hi,\n\nI'd like to send you an email.\n\nBest Regards\n\nMe." | ||
− | sendmail(mailto, mailfrom=mailfrom, mailsubject=mailsubject, mailtext=mailtext, attachments=[attachment1]) | + | sendmail(mailto, mailfrom=mailfrom, mailsubject=mailsubject, mailtext=mailtext, attachments=[attachment1,attachment2]) |
return | return | ||
Line 38: | Line 40: | ||
outer = MIMEMultipart() | outer = MIMEMultipart() | ||
outer['Subject'] = mailsubject | outer['Subject'] = mailsubject | ||
− | outer['To'] = mailto | + | outer['To'] = ",".join(mailto) |
if mailfrom != '': | if mailfrom != '': | ||
outer['From'] = mailfrom | outer['From'] = mailfrom |
Revision as of 13:18, 1 October 2018
Sending mail with sendmail
sendmail -t < <messagefile>
- Send the email as in <messagefile>
The email headers are in <messagefile>. That should look like:
From: me@mydomain.tld
To: user@domain.tld
Subject: Subject of your mail
email text
mailx -s Subject -a <attachmentfile> email@domain.tld
- Send email with attachment after entering optional text and an EOT (CTRL-D).
Python email sender found in [python docs]
def main():
attachement1 = filepath
attachement2 = filepath
mailto = ['you@domain.tld']
mailfrom = 'me@domain.tld'
mailsubject = 'What this is about'
mailtext = "Hi,\n\nI'd like to send you an email.\n\nBest Regards\n\nMe."
sendmail(mailto, mailfrom=mailfrom, mailsubject=mailsubject, mailtext=mailtext, attachments=[attachment1,attachment2])
return
def sendmail(mailto,mailfrom = '',mailsubject = '',mailtext = '',attachment = ''):
import smtplib
from email import encoders
from email.message import Message
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
outer = MIMEMultipart()
outer['Subject'] = mailsubject
outer['To'] = ",".join(mailto)
if mailfrom != '':
outer['From'] = mailfrom
msg = MIMEText(mailtext,_subtype='plain')
outer.attach(msg)
if attachments != '':
for attachment in attachments:
filename = attachment.split('/')[-1]
ctype = 'application/octet-stream'
maintype, subtype = ctype.split('/', 1)
fp = open(attachment, 'rb')
msg = MIMEBase(maintype, subtype)
msg.set_payload(fp.read())
fp.close()
# Encode the payload using Base64
encoders.encode_base64(msg)
# Set the filename parameter
msg.add_header('Content-Disposition', 'attachment', filename=filename)
outer.attach(msg)
composed = outer.as_string()
s = smtplib.SMTP('localhost')
s.sendmail(mailfrom, mailto , composed)
s.quit()
return
main()