Don't use `flake8: noqa`.
[mailman.git] / src / mailman / mta / deliver.py
blobd1f87db076b823a4f05f75bac57b1e1d1b40db13
1 # Copyright (C) 2009-2016 by the Free Software Foundation, Inc.
3 # This file is part of GNU Mailman.
5 # GNU Mailman is free software: you can redistribute it and/or modify it under
6 # the terms of the GNU General Public License as published by the Free
7 # Software Foundation, either version 3 of the License, or (at your option)
8 # any later version.
10 # GNU Mailman is distributed in the hope that it will be useful, but WITHOUT
11 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
13 # more details.
15 # You should have received a copy of the GNU General Public License along with
16 # GNU Mailman. If not, see <http://www.gnu.org/licenses/>.
18 """Generic delivery."""
20 import time
21 import logging
23 from mailman import public
24 from mailman.config import config
25 from mailman.interfaces.mailinglist import Personalization
26 from mailman.interfaces.mta import SomeRecipientsFailed
27 from mailman.mta.decorating import DecoratingMixin
28 from mailman.mta.personalized import PersonalizedMixin
29 from mailman.mta.verp import VERPMixin
30 from mailman.mta.base import IndividualDelivery
31 from mailman.mta.bulk import BulkDelivery
32 from mailman.utilities.string import expand
35 COMMA = ','
36 log = logging.getLogger('mailman.smtp')
39 @public
40 class Deliver(VERPMixin, DecoratingMixin, PersonalizedMixin,
41 IndividualDelivery):
42 """Deliver one message to one recipient.
44 All current individualized features are avaialble to this
45 `IMailTransportAgentDelivery` instance:
47 * VERP
48 * Full Personalization
49 * Header/Footer decoration
50 """
52 def __init__(self):
53 super().__init__()
54 self.callbacks.extend([
55 self.avoid_duplicates,
56 self.decorate,
57 self.personalize_to,
61 @public
62 def deliver(mlist, msg, msgdata):
63 """Deliver a message to the outgoing mail server."""
64 # If there are no recipients, there's nothing to do.
65 recipients = msgdata.get('recipients')
66 if not recipients:
67 # Could be None, could be an empty sequence.
68 return
69 # Which delivery agent should we use? Several situations can cause us to
70 # use individual delivery. If not specified, use bulk delivery. See the
71 # to-outgoing handler for when the 'verp' key is set in the metadata.
72 if msgdata.get('verp', False):
73 agent = Deliver()
74 elif mlist.personalize != Personalization.none:
75 agent = Deliver()
76 else:
77 agent = BulkDelivery(int(config.mta.max_recipients))
78 log.debug('Using agent: %s', agent)
79 # Keep track of the original recipients and the original sender for
80 # logging purposes.
81 original_recipients = msgdata['recipients']
82 original_sender = msgdata.get('original-sender', msg.sender)
83 # Let the agent attempt to deliver to the recipients. Record all failures
84 # for re-delivery later.
85 t0 = time.time()
86 refused = agent.deliver(mlist, msg, msgdata)
87 t1 = time.time()
88 # Log this posting.
89 size = getattr(msg, 'original_size', msgdata.get('original_size'))
90 if size is None:
91 size = len(msg.as_string())
92 substitutions = dict(
93 msgid = msg.get('message-id', 'n/a'), # noqa
94 listname = mlist.fqdn_listname, # noqa
95 sender = original_sender, # noqa
96 recip = len(original_recipients), # noqa
97 size = size, # noqa
98 time = t1 - t0, # noqa
99 refused = len(refused), # noqa
100 smtpcode = 'n/a', # noqa
101 smtpmsg = 'n/a', # noqa
103 template = config.logging.smtp.every
104 if template.lower() != 'no':
105 log.info('%s', expand(template, substitutions))
106 if refused:
107 template = config.logging.smtp.refused
108 if template.lower() != 'no':
109 log.info('%s', expand(template, substitutions))
110 else:
111 # Log the successful post, but if it was not destined to the mailing
112 # list (e.g. to the owner or admin), print the actual recipients
113 # instead of just the number.
114 if not msgdata.get('tolist', False):
115 recips = msg.get_all('to', [])
116 recips.extend(msg.get_all('cc', []))
117 substitutions['recips'] = COMMA.join(recips)
118 template = config.logging.smtp.success
119 if template.lower() != 'no':
120 log.info('%s', expand(template, substitutions))
121 # Process any failed deliveries.
122 temporary_failures = []
123 permanent_failures = []
124 for recipient, (code, smtp_message) in refused.items():
125 # RFC 5321, $4.5.3.1.10 says:
127 # RFC 821 [1] incorrectly listed the error where an SMTP server
128 # exhausts its implementation limit on the number of RCPT commands
129 # ("too many recipients") as having reply code 552. The correct
130 # reply code for this condition is 452. Clients SHOULD treat a 552
131 # code in this case as a temporary, rather than permanent, failure
132 # so the logic below works.
134 if code >= 500 and code != 552:
135 # A permanent failure
136 permanent_failures.append(recipient)
137 else:
138 # Deal with persistent transient failures by queuing them up for
139 # future delivery. TBD: this could generate lots of log entries!
140 temporary_failures.append(recipient)
141 template = config.logging.smtp.failure
142 if template.lower() != 'no':
143 substitutions.update(
144 recip = recipient, # noqa
145 smtpcode = code, # noqa
146 smtpmsg = smtp_message, # noqa
148 log.info('%s', expand(template, substitutions))
149 # Return the results
150 if temporary_failures or permanent_failures:
151 raise SomeRecipientsFailed(temporary_failures, permanent_failures)