How to Send Email Attachments

How to send email attachments?

Here's another:

import smtplib
from os.path import basename
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate


def send_mail(send_from, send_to, subject, text, files=None,
server="127.0.0.1"):
assert isinstance(send_to, list)

msg = MIMEMultipart()
msg['From'] = send_from
msg['To'] = COMMASPACE.join(send_to)
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = subject

msg.attach(MIMEText(text))

for f in files or []:
with open(f, "rb") as fil:
part = MIMEApplication(
fil.read(),
Name=basename(f)
)
# After the file is closed
part['Content-Disposition'] = 'attachment; filename="%s"' % basename(f)
msg.attach(part)


smtp = smtplib.SMTP(server)
smtp.sendmail(send_from, send_to, msg.as_string())
smtp.close()

It's much the same as the first example... But it should be easier to drop in.

Is there a quick way to send email attachments in python using SMTP without knowing the file type in advance?

SMTP doesn't care what the attachment contains. Just put it as application/octet-stream and hope the recipient knows what to do with it. But make sure you spell the MIME type correctly. ("Octet" is just a fancy way to say "8-bit byte".)

Also, Content-Decomposition is not a valid MIME header name; you want Content-Disposition.

These horrible typos are probably why you observed problems in some clients. They can't guess what you mean when you misspell critical technical keywords.

More fundamentally, you appear to have copy/pasted email code from several years back for both of your attempts. The current Python 3.6+ email library code is much more readable and versatile. Probably throw away what you have and start over with the examples in the documentation.

If you can guess correctly the MIME type of the file you are transmitting, adding that information to the MIME headers would be useful; but automating this for arbitrary attachment types is unlikely to be helpful. If your guessing logic guesses wrong, you are just making things harder by claiming that you know when you don't.

So, I don't particularly recommend even trying; but if you want to verify for yourself that this is futile, try the mimetypes.guess_type method from the standard library. The documentation suggests that this just contains canned guesses for a collection of file name extensions; a more thorough approach would be to use the actual contents of the file and libmagic or similar to attempt to identify what it is.

using mailto to send email with an attachment

Nope, this is not possible at all. There is no provision for it in the mailto: protocol, and it would be a gaping security hole if it were possible.

The best idea to send a file, but have the client send the E-Mail that I can think of is:

  • Have the user choose a file
  • Upload the file to a server
  • Have the server return a random file name after upload
  • Build a mailto: link that contains the URL to the uploaded file in the message body

How to send an email with attachments in Go

I created gomail for this purpose. It supports attachments as well as multipart emails and encoding of non-ASCII characters. It is well documented and tested.

Here is an example:

package main

func main() {
m := gomail.NewMessage()
m.SetHeader("From", "alex@example.com")
m.SetHeader("To", "bob@example.com", "cora@example.com")
m.SetAddressHeader("Cc", "dan@example.com", "Dan")
m.SetHeader("Subject", "Hello!")
m.SetBody("text/html", "Hello <b>Bob</b> and <i>Cora</i>!")
m.Attach("/home/Alex/lolcat.jpg")

d := gomail.NewPlainDialer("smtp.example.com", 587, "user", "123456")

// Send the email to Bob, Cora and Dan.
if err := d.DialAndSend(m); err != nil {
panic(err)
}
}

How to send emails with conditional attachments?

Something like this:

If checkbox1.Value And checkbox2.Value Then
Mailtje.Attachments.Add "C:\Test\Pic1.jpg" 'use the full path
End If
If checkbox3.Value Then
Mailtje.Attachments.Add "C:\Test\Pic2.jpg"
End If


Related Topics



Leave a reply



Submit