1
+ import smtplib
2
+ from pathlib import Path
3
+ from email .mime .multipart import MIMEMultipart
4
+ from email .mime .base import MIMEBase
5
+ from email .mime .text import MIMEText
6
+ from email .utils import COMMASPACE , formatdate
7
+ from email import encoders
8
+
9
+
10
+ def send_mail (send_from , send_to , subject , message , files = [],
11
+ server = "localhost" , port = 587 , username = '' , password = '' ,
12
+ use_tls = True ):
13
+ """Compose and send email with provided info and attachments.
14
+
15
+ Args:
16
+ send_from (str): from name
17
+ send_to (list[str]): to name(s)
18
+ subject (str): message title
19
+ message (str): message body
20
+ files (list[str]): list of file paths to be attached to email
21
+ server (str): mail server host name
22
+ port (int): port number
23
+ username (str): server auth username
24
+ password (str): server auth password
25
+ use_tls (bool): use TLS mode
26
+ """
27
+
28
+ msg = MIMEMultipart ()
29
+ msg ['From' ] = send_from
30
+ msg ['To' ] = COMMASPACE .join (send_to )
31
+ msg ['Date' ] = formatdate (localtime = True )
32
+ msg ['Subject' ] = subject
33
+
34
+ msg .attach (MIMEText (message ))
35
+
36
+ for path in files :
37
+ part = MIMEBase ('application' , "octet-stream" )
38
+ with open (path , 'rb' ) as file :
39
+ part .set_payload (file .read ())
40
+ encoders .encode_base64 (part )
41
+ part .add_header ('Content-Disposition' ,
42
+ 'attachment; filename={}' .format (Path (path ).name ))
43
+ msg .attach (part )
44
+
45
+ smtp = smtplib .SMTP (server , port )
46
+ if use_tls :
47
+ smtp .starttls ()
48
+ smtp .login (username , password )
49
+ smtp .sendmail (send_from , send_to , msg .as_string ())
50
+ smtp .quit ()
0 commit comments