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
How to Expand the Output Display to See More Columns of a Pandas Dataframe
How to Melt a Pandas Dataframe
Installing Python Module Within Code
How to Convert All Strings in a List of Lists to Integers
Are List-Comprehensions and Functional Functions Faster Than "For Loops"
How to Save and Load Cookies Using Python + Selenium Webdriver
How to Identify on Which Os Python Is Running On
Find Unique Rows in Numpy.Array
Tkinter - Executing Functions Over Time
"Inconsistent Use of Tabs and Spaces in Indentation"
How Do Python'S Any and All Functions Work
Pygame - How to Display Text With Font & Color
Django Csrf Check Failing With an Ajax Post Request
Is There a Portable Way to Get the Current Username in Python