@ -23,8 +23,10 @@
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import dataclasses
import re
import smtplib
import typing as t
from email . mime . text import MIMEText
from email . mime . application import MIMEApplication
from email . mime . multipart import MIMEMultipart
@ -282,6 +284,13 @@ EMAIL_TEMPLATES = (
)
@dataclasses . dataclass
class EmailMessage :
recipient : str
to_addrs : t . List [ str ]
body : str
class NotifyEmail ( NotifyBase ) :
"""
A wrapper to Email Notifications
@ -659,15 +668,14 @@ class NotifyEmail(NotifyBase):
# Initialize our default from name
from_name = self . from_name if self . from_name else self . app_desc
# error tracking (used for function return)
has_error = False
if not self . targets :
# There is no one to email; we're done
self . logger . warning (
' There are no Email recipients to notify ' )
return False
messages : t . List [ EmailMessage ] = [ ]
# Create a copy of the targets list
emails = list ( self . targets )
while len ( emails ) :
@ -778,6 +786,19 @@ class NotifyEmail(NotifyBase):
if reply_to :
base [ ' Reply-To ' ] = ' , ' . join ( reply_to )
message = EmailMessage (
recipient = to_addr ,
to_addrs = [ to_addr ] + list ( cc ) + list ( bcc ) ,
body = base . as_string ( ) )
messages . append ( message )
return self . submit ( messages )
def submit ( self , messages : t . List [ EmailMessage ] ) :
# error tracking (used for function return)
has_error = False
# bind the socket variable to the current namespace
socket = None
@ -808,22 +829,30 @@ class NotifyEmail(NotifyBase):
self . logger . debug ( ' Applying user credentials... ' )
socket . login ( self . user , self . password )
# Send the email
# Send the emails
for message in messages :
try :
socket . sendmail (
self . from_addr ,
[ to_addr ] + list ( cc ) + list ( bcc ) ,
base . as_string ( ) )
message . to_addrs ,
message . body )
self . logger . info (
' Sent Email notification to " {} " . ' . format ( to_addr ) )
f ' Sent Email notification to " { message . recipient } " . ' )
except ( SocketError , smtplib . SMTPException , RuntimeError ) as e :
self . logger . warning (
f ' Sending email to " { message . recipient } " failed. '
f ' Reason: { e } ' )
# Mark as failure
has_error = True
except ( SocketError , smtplib . SMTPException , RuntimeError ) as e :
self . logger . warning (
' A Connection error occurred sending Email '
' notification to {} . ' . format ( self . smtp_host ) )
self . logger . debug ( ' Socket Exception: %s ' % str ( e ) )
f ' Connection error while submitting email to { self . smtp_host } . '
f ' Reason: { e } ' )
# Mark our failure
# Mark as failure
has_error = True
finally :