]>
git.ipfire.org Git - ipfire.org.git/blob - src/backend/messages.py
4 import email
.mime
.multipart
14 import tornado
.template
16 from . import accounts
19 from .decorators
import *
21 class Messages(misc
.Object
):
24 return Queue(self
.backend
)
27 def template_loader(self
):
29 Creates a new template loader
31 templates_dir
= self
.backend
.config
.get("global", "templates_dir")
34 return tornado
.template
.Loader(templates_dir
, autoescape
=None)
36 def make_recipient(self
, recipient
):
37 # Use the contact instead of the account
38 if isinstance(recipient
, accounts
.Account
):
39 recipient
= recipient
.email_to
41 # Fall back to pass on strings
45 return email
.utils
.make_msgid("ipfire", domain
="ipfire.org")
48 def bounce_email_address(self
):
49 return self
.settings
.get("bounce_email_address")
51 def _send(self
, message
, sender
=None, priority
=0):
52 res
= self
.db
.get("INSERT INTO messages(message, priority) \
53 VALUES(%s, %s) RETURNING id", message
, priority
)
55 logging
.debug("Message queued with ID %s" % res
.id)
57 def send(self
, message
, priority
=0, headers
={}):
58 # Convert message from string
59 if not isinstance(message
, email
.message
.Message
):
60 message
= email
.message_from_string(message
)
62 # Add a message ID if non exsist
63 if not "Message-Id" in message
and not "Message-ID" in message
:
64 message
.add_header("Message-Id", self
.make_msgid())
69 message
.replace_header(k
, v
)
71 message
.add_header(k
, v
)
73 # Add date if the message doesn't have one already
74 if "Date" not in message
:
75 message
.add_header("Date", email
.utils
.formatdate())
77 # Send any errors to the bounce address
78 if self
.bounce_email_address
:
79 message
.add_header("Errors-To", "<%s>" % self
.bounce_email_address
)
82 self
._send
(message
.as_string(), priority
=priority
)
84 def send_template(self
, template_name
,
85 sender
=None, priority
=0, headers
={}, **kwargs
):
87 Send a message based on the given template
89 locale
= tornado
.locale
.get("en_US")
91 # Create the required namespace to render the message
94 "backend" : self
.backend
,
98 "_" : locale
.translate
,
100 namespace
.update(kwargs
)
102 # Create an alternating multipart message to show HTML or text
103 message
= email
.mime
.multipart
.MIMEMultipart("alternative")
105 for extension
, mimetype
in (("txt", "plain"), ("html", "html")):
107 t
= self
.template_loader
.load("%s.%s" % (template_name
, extension
))
109 # Ignore if the HTML template does not exist
110 if extension
== "html":
113 # Raise all other exceptions
118 message_part
= t
.generate(**namespace
)
120 # Reset the rendered template when it could not be rendered
122 self
.template_loader
.reset()
125 # Parse the message and extract the header
126 message_part
= email
.message_from_string(message_part
.decode())
128 for header
in message_part
:
129 value
= message_part
[header
]
131 # Make sure addresses are properly encoded
132 realname
, address
= email
.utils
.parseaddr(value
)
133 if realname
and address
:
134 value
= email
.utils
.formataddr((realname
, address
))
137 message
.replace_header(header
, value
)
139 message
.add_header(header
, value
)
141 # Create a MIMEText object out of it
142 message_part
= email
.mime
.text
.MIMEText(
143 message_part
.get_payload(), mimetype
)
145 # Attach the parts to the mime container.
146 # According to RFC2046, the last part of a multipart message
148 message
.attach(message_part
)
151 self
.send(message
, priority
=priority
, headers
=headers
)
153 # In debug mode, re-compile the templates with every request
154 if self
.backend
.debug
:
155 self
.template_loader
.reset()
157 async def send_cli(self
, template
, recipient
):
159 Send a test message from the CLI
161 account
= self
.backend
.accounts
.get_by_mail(recipient
)
163 posts
= list(self
.backend
.blog
.get_newest(limit
=5))
167 "first_name" : account
.first_name
,
168 "last_name" : account
.last_name
,
170 "email" : account
.email
,
172 # Random activation/reset codes
173 "activation_code" : util
.random_string(36),
174 "reset_code" : util
.random_string(64),
176 # The latest blog post
177 "post" : random
.choice(posts
),
180 return self
.send_template(template
, **kwargs
)
183 class Queue(misc
.Object
):
184 context
= ssl
.create_default_context()
188 return self
.db
.query("SELECT * FROM messages \
189 WHERE time_sent IS NULL \
190 ORDER BY priority DESC, time_created ASC")
195 Connection to the local mail relay
197 hostname
= socket
.getfqdn()
199 # Open SMTP connection
200 conn
= smtplib
.SMTP(hostname
)
202 # Start TLS connection
203 conn
.starttls(context
=self
.context
)
207 async def send_all(self
):
209 for message
in self
.messages
:
212 logging
.debug("All messages sent")
214 def send(self
, message
):
216 Delivers the given message the local mail relay
218 # Parse the message from what is in the database
219 msg
= email
.message_from_string(message
.message
)
221 logging
.debug("Sending a message %s to: %s" % (
222 msg
.get("Subject"), msg
.get("To"),
226 rejected_recipients
= {}
228 # Try delivering the email
230 rejected_recipients
= self
.relay
.send_message(msg
)
232 except smtplib
.SMTPRecipientsRefused
as e
:
233 rejected_recipients
= e
.recipients
235 except smtplib
.SMTPException
as e
:
236 logging
.error("SMTP Exception: %s" % e
)
237 error_messages
.append("%s" % e
)
239 # Log all emails that could not be delivered
240 for recipient
in rejected_recipients
:
241 code
, reason
= rejected_recipients
[recipient
]
243 error_messages
.append("Recipient refused: %s - %s (%s)" % \
244 (recipient
, code
, reason
.decode()))
247 self
.db
.execute("UPDATE messages SET error_message = %s \
248 WHERE id = %s", "; ".join(error_messages
), message
.id)
250 logging
.error("Could not send email: %s" % message
.id)
251 for line
in error_messages
:
254 # After the email has been successfully sent, we mark it as such
255 self
.db
.execute("UPDATE messages SET time_sent = NOW() \
256 WHERE id = %s", message
.id)
259 logging
.debug("Cleaning up message queue")
261 self
.db
.execute("DELETE FROM messages \
262 WHERE time_sent IS NOT NULL AND time_sent <= NOW() - '30 day'::interval")