Python3: 画像ファイルをアップロードしてメール添付で送る

![upload_send_python_apr18.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/179446/b8b84a1e-2a6a-aecf-0321-ccf60fddeeda.png)


フォルダーの構造

```text
$ tree
.
├── data_work
├── index.html -> upload_send_python.html
├── mail_attache_send.py
├── send_starttls.py
├── upload_send_python.html
└── upload_send_python.py
```

```html:upload_send_python.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>upload_send_python (Apr/18/2021)</title>
</head>
<body>
<h2>Upload Send Python</h2>
<form method="post" action="upload_send_python.py" enctype="multipart/form-data">
<input type="file" name="files"  multiple>
<p><input type="submit" value="送信する"></p>
</form>

<blockquote>
<p>File will be uploaded to ./data_work.</p>
</blockquote>
<hr />
Apr/18/2021 AM 08:25<p />
</body>
</html>
```

```py:upload_send_python.py
#! /usr/bin/python3
# -*- coding: utf-8 -*-
#
#	upload_send_python.py
#
#					Apr/18/2021
#
# --------------------------------------------------------------------
import os
import sys
import cgi
from dotenv import load_dotenv
#
from mail_attache_send import mail_attache_send_proc
# --------------------------------------------------------------------
def single_upload_file_proc_exec(item,path):
	try:
		chunk = item.file.read()
		if chunk:
			fout = open(path,mode='wb')
			fout.write(chunk)
			print(path + "<br />")
			fout.close()
			os.chmod(path, 0o666)
	except Exception as ee:
		print("*** error *** single_upload_file_proc_exec ***<br />")
		print(path + "<br />")
		print(str (ee))
		print("<br />")
# --------------------------------------------------------------------
def single_upload_file_proc(upload_dir,item,mail):
	filename = item.filename
	path = os.path.join(upload_dir,os.path.basename(filename))
	single_upload_file_proc_exec(item,path)
#
	try:
		mail_attache_send_proc(mail,path)
	except Exception as ee:
		print("*** error *** mail_attache_send_proc ***<br />")
		print(str (ee))
		print("<br />")

# --------------------------------------------------------------------
def multi_uploaded_file_proc(upload_dir,fileitem,mail):
#
	for item in fileitem:
		single_upload_file_proc(upload_dir,item)
#
# --------------------------------------------------------------------
dotenv_path = '.env'
load_dotenv(dotenv_path)
mail = {}
mail['server'] = os.environ.get("SERVER")
mail['port'] = os.environ.get("PORT")
mail['usr'] = os.environ.get("USR")
mail['password'] = os.environ.get("PASSWORD")
mail['from'] = os.environ.get("FROM")
mail['to'] = os.environ.get("TO")
#
upload_dir = "./data_work"
#
print("Content-Type: text/html")
print("")

form = cgi.FieldStorage()
if "files" in form:
	fileitem = form["files"]
	print(isinstance (fileitem,list))
	print("<br />")
	if (isinstance(fileitem,list)):
		multi_uploaded_file_proc(upload_dir,fileitem,mail)
	else:
		single_upload_file_proc(upload_dir,fileitem,mail)
else:
	print("*** Select files ***<br />")

print("*** end ***<br />")
#
# --------------------------------------------------------------------
```

```mail_attache_send.py
#
#	mail_attache_send.py
#
#						Apr/18/2021	
# --------------------------------------------------------------------
import	os
import	sys
import	socket
import	email
from email.mime.text import MIMEText
from email.utils import formatdate
from email.message import EmailMessage
import imghdr
# --------------------------------------------------------------------
from send_starttls import send_starttls_proc
# --------------------------------------------------------------------
def attach_image_proc(message,img_data,filename):
    try:
        message.add_attachment(img_data,maintype='image',
            subtype=imghdr.what(None,img_data),filename=filename)
    except Exception as ee:
        sys.stderr.write("*** error *** in message.add_attachment ***\n")
        sys.stderr.write(str(ee) + "\n")
#
    return message
# --------------------------------------------------------------------
def create_message_proc(mail,file_attach):
	message = EmailMessage()
	contents = 'Hello, Good Afternoon! on Apr/18/2021 AM 07:21\n'
	contents += 'Apr/18/2021 AM 20:03\n'
	contents += 'こんにちは。\n'
	contents += 'python3\n'
	contents += ' ' + socket.gethostname ()

	message.set_content(contents)

	message['Subject'] = 'Hello Apr/18/2021 AM 07:21'
	message['From'] = mail['from']
	message['To'] = mail['to']
	message['Date'] = formatdate ()
#
	fp = open(file_attach,'rb')
	img_data = fp.read()
	fp.close()
#
	for suffix in [".jpg",".png",".bmp","gif"]:
		if (file_attach.endswith(suffix)):
			message = attach_image_proc(message,img_data,file_attach)
#
	return message
# --------------------------------------------------------------------
def mail_attache_send_proc(mail,file_attache):
#
	message = create_message_proc(mail,file_attache)

	send_starttls_proc (mail,message)
#
# --------------------------------------------------------------------
```

次のファイルはこちらです。
[Python3: Starttls でメールの送信](https://qiita.com/ekzemplaro/items/c248b52a6f36947af080)

```text
send_starttls.py
.env
```

関連情報
[Python3: メールの送信 （添付ファイル付き）](https://qiita.com/ekzemplaro/items/cf78099839d311955c69)
[Python3: ファイルのアップロード (cgi)](https://qiita.com/ekzemplaro/items/214394d653e4ee8bd8b8)