cl-smtp.lisp 25.6 KB
Newer Older
Jan Idzikowski's avatar
Jan Idzikowski committed
1
2
3
4
;;; -*- mode: Lisp -*-
	
;;; This file is part of CL-SMTP, the Lisp SMTP Client

5
;;; Copyright (C) 2004/2005/2006/2007/2008/2009/2010 Jan Idzikowski
Jan Idzikowski's avatar
Jan Idzikowski committed
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

;;; This library is free software; you can redistribute it and/or
;;; modify it under the terms of the Lisp Lesser General Public License
;;; (http://opensource.franz.com/preamble.html), known as the LLGPL.

;;; This library is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;;; Lisp Lesser GNU General Public License for more details.

;;; File: cl-smtp.lisp
;;; Description: main smtp client logic

(in-package :cl-smtp)

21
(defparameter *x-mailer* (format nil "cl-smtp (~A ~A)" 
Jan Idzikowski's avatar
Jan Idzikowski committed
22
23
24
25
26
				 (lisp-implementation-type)
				 (lisp-implementation-version)))

(defun check-arg (arg name)
  (cond
27
28
   ((or (stringp arg)
        (pathnamep arg))
Jan Idzikowski's avatar
Jan Idzikowski committed
29
30
31
32
33
34
    (list arg))
   ((listp arg)
    arg)
   (t
    (error "the \"~A\" argument is not a string or cons" name))))

Jan Idzikowski's avatar
Jan Idzikowski committed
35
(eval-when (:compile-toplevel :load-toplevel :execute)
36
  (defvar *return-newline* #.(format nil "~C~C" #\Return #\NewLine)))
Jan Idzikowski's avatar
Jan Idzikowski committed
37

Jan Idzikowski's avatar
Jan Idzikowski committed
38
(defun mask-dot (str)
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
   "Replace all occurences of single line #\. with #\.#\." 
     (with-output-to-string (s)
       (mask-dot-stream str s)))

(defun mask-dot-stream (str stream)
  "Replace all occurences of single line #\. with #\.#\."
  (let ((l (length str)))
    (loop for c across str
       for i from 0
       for pc = (when (> i 0) (elt str (1- i)))
       for nc = (when (< (1+ i) l)  (elt str (1+ i)))
       do (if (and (eq c #\.) (or (eq pc #\Newline) (not pc))
                   (or (eq nc #\Return) (eq nc #\Newline) (not nc)))
              (write-sequence ".." stream)
              (write-char c stream)))))
Jan Idzikowski's avatar
Jan Idzikowski committed
54

55
56
57
58
59
(defun string-to-base64-string (str &key (external-format :utf-8)
                                (columns 80))
  (let ((exformat (flex:make-external-format external-format)))
  #+allegro (excl:usb8-array-to-base64-string 
             (flex:string-to-octets str :external-format exformat)
60
61
             :wrap-at-column (if (and (numberp columns) (= columns 0))
                                  nil columns))
62
63
64
65
66
67
68
  #-allegro (cl-base64:usb8-array-to-base64-string 
             (flex:string-to-octets str :external-format exformat)
             :columns columns)))

(defun string-has-non-ascii (str)
  (loop for c across str
     when (< 127 (char-code c)) do (return t)))
69

70
71
(defun rfc2045-q-encode-string (str &key (external-format :utf-8))
  (let ((line-has-non-ascii nil)
72
73
        (last-line-break 0)
        (len (length str))
74
        (exformat (flex:make-external-format external-format)))
75
    (with-output-to-string (s)
76
77
78
79
80
81
82
83
      (loop for c across str
         for n from 0 to len
         for column = (- n last-line-break)
         do
           (when (>= column 74)
             (write-blank-line s)
             (write-char #\Space s)
             (setf last-line-break n))
84
           (cond
85
86
87
88
             ((char= c #\NewLine)
              (setf last-line-break n)
              (write-blank-line s)
              (write-char #\Space s))
89
90
             ((< 127 (char-code c))
              (unless line-has-non-ascii
91
92
                (format s "=?~A?Q?" 
                        (string-upcase (symbol-name external-format)))
93
94
95
                (setf line-has-non-ascii t))
              (loop for byte across (flex:string-to-octets 
                                     (make-string 1 :initial-element c)
96
                                     :external-format exformat)
97
                 do (format s "~:@(=~2,'0X~)" byte)))
98
99
             (t 
              (when line-has-non-ascii
100
                (write-sequence "?=" s)
101
                (setf line-has-non-ascii nil))
102
103
              (unless (char= c #\Return)
                (write-char c s)))))
104
105
106
      (when line-has-non-ascii
        (format s "?=")))))

107
108
109
110
111
112
113
114
115
(defun rfc2045-q-encode-string-to-stream (str stream 
                                          &key (external-format :utf-8) 
                                          (columns 74))
  (let ((exformat (flex:make-external-format external-format))
        (last-line-break 0)
        (len (length str)))
    (loop for c across str
          for n from 0 to len 
          for column = (- n last-line-break)
116
          for nc = (when (< (1+ n) len) (elt str (1+ n)))
117
118
119
120
121
122
       do
         (when (>= column columns)
           (write-char #\= stream)
           (write-blank-line stream)
           (setf last-line-break n))
         (cond
123
           ((and (char= c #\.) (= n last-line-break))
124
125
            (write-char #\. stream)
            (write-char #\. stream))
126
           ((char= c #\NewLine)
127
            (setf last-line-break (1+ n))
Jan Idzikowski's avatar
Jan Idzikowski committed
128
            (write-blank-line stream))
129
130
           ((or (char= c #\Space)
                (char= c #\Tab))
131
            (if (eq nc #\NewLine)
132
133
134
135
136
137
138
139
140
141
142
143
144
145
                (format stream "~:@(=~2,'0X~)" (char-code c))
                (write-char c stream)))
           ((or (< 127 (char-code c))
                (> 33 (char-code c))
                (char= c #\=))
            (loop for byte across (flex:string-to-octets 
                                     (make-string 1 :initial-element c)
                                     :external-format exformat)
                 do (format stream "~:@(=~2,'0X~)" byte)))
           (t
            (write-char c stream))
           ))
    ))

146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
(defun substitute-return-newline (str)
  "Replace all occurences of \r\n in STR with spaces"
  (let ((resultstr ""))
    (labels ((mask (tempstr)
	       (let ((n (search *return-newline* tempstr)))
		 (cond
                   (n
                    (setf resultstr (concatenate 'string resultstr 
                                                 (subseq tempstr 0 n)
                                                 " "))
                    (mask (subseq tempstr (+ n 2))))
                   (t
                    (setf resultstr (concatenate 'string resultstr 
                                                 tempstr)))))))
      (mask str))
    resultstr))

Jan Idzikowski's avatar
Jan Idzikowski committed
163
164
165
166
167
168
169
170
171
172
(define-condition smtp-error (error)
  ())

(define-condition smtp-protocol-error (smtp-error)
  ((command :initarg :command :reader command)
   (expected-response-code :initarg :expected-response-code :reader expected-response-code)
   (response-code :initarg :response-code :reader response-code)
   (response-message :initarg :response-message :reader response-message))
  (:report (lambda (condition stream)
             (print-unreadable-object (condition stream :type t)
173
               (format stream "a command failed:~%command: ~S expected: ~A response-code: ~A response-message: ~A"
Jan Idzikowski's avatar
Jan Idzikowski committed
174
175
                       (command condition)
                       (expected-response-code condition)
176
                       (response-code condition)
Jan Idzikowski's avatar
Jan Idzikowski committed
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
                       (response-message condition))))))

(define-condition rcpt-failed (smtp-protocol-error)
  ((recipient :initarg :recipient
              :reader recipient))
  (:report (lambda (condition stream)
             (print-unreadable-object (condition stream :type t)
               (format stream "while trying to send email through SMTP, the server rejected the recipient ~A: ~A"
                       (recipient condition)
                       (response-message condition))))))

(defun smtp-command (stream command expected-response-code
                     &key (condition-class 'smtp-protocol-error) 
                     condition-arguments)
  (when command
    (write-to-smtp stream command))
  (multiple-value-bind (code msgstr lines)
      (read-from-smtp stream)
    (when (/= code expected-response-code)
      (apply #'error
             condition-class
             (append condition-arguments
                     (list :command command
                           :expected-response-code expected-response-code
                           :response-code code
                           :response-message msgstr))))
203
    (append lines (list msgstr))))
Jan Idzikowski's avatar
Jan Idzikowski committed
204

205
(defun do-with-smtp-mail (host envelope-sender to thunk &key port authentication ssl local-hostname (external-format :utf-8))
206
207
208
  (usocket:with-client-socket (socket stream host port 
                                      :element-type '(unsigned-byte 8))
    (setf stream (flexi-streams:make-flexi-stream 
209
210
211
212
                  stream
                  :external-format 
                  (flexi-streams:make-external-format 
                   external-format :eol-style :lf)))
Jan Idzikowski's avatar
Jan Idzikowski committed
213
214
215
216
    (let ((stream (smtp-handshake stream
                                  :authentication authentication 
                                  :ssl ssl
                                  :local-hostname local-hostname)))
217
      (initiate-smtp-mail stream envelope-sender to)
218
      (funcall thunk stream)
Jan Idzikowski's avatar
Jan Idzikowski committed
219
220
      (finish-smtp-mail stream))))

221
(defmacro with-smtp-mail ((stream-var host envelope-sender to &key ssl (port (if (eq :tls ssl) 465 25)) authentication local-hostname (external-format :utf-8))
Jan Idzikowski's avatar
Jan Idzikowski committed
222
223
224
225
226
227
228
                          &body body)
  "Encapsulate a SMTP MAIl conversation.  A connection to the SMTP
   server on HOST and PORT is established and a MAIL command is
   initiated with FROM being the mail sender and TO being the list of
   recipients.  BODY is evaluated with STREAM-VAR being the stream
   connected to the remote SMTP server.  BODY is expected to write the
   RFC2821 message (headers and body) to STREAM-VAR."
229
  `(do-with-smtp-mail ,host ,envelope-sender ,to
Jan Idzikowski's avatar
Jan Idzikowski committed
230
231
232
233
                      (lambda (,stream-var) ,@body)
                      :port ,port
                      :authentication ,authentication 
                      :ssl ,ssl
234
235
                      :local-hostname ,local-hostname
                      :external-format ,external-format))
Jan Idzikowski's avatar
Jan Idzikowski committed
236
237

(defun send-email (host from to subject message 
Jan Idzikowski's avatar
Jan Idzikowski committed
238
		   &key ssl (port (if (eq :tls ssl) 465 25)) cc bcc reply-to extra-headers
239
		   html-message display-name authentication
240
241
		   attachments (buffer-size 256) envelope-sender 
                   (external-format :utf-8) local-hostname)
Jan Idzikowski's avatar
Jan Idzikowski committed
242
243
244
245
  (send-smtp host from (check-arg to "to") subject (mask-dot message)
	     :port port :cc (check-arg cc "cc") :bcc (check-arg bcc "bcc")
	     :reply-to reply-to 
	     :extra-headers extra-headers
246
	     :html-message html-message
247
	     :display-name display-name
248
249
250
251
	     :authentication authentication
	     :attachments (check-arg attachments "attachments")
	     :buffer-size (if (numberp buffer-size) 
			      buffer-size
252
			      256)
253
	     :envelope-sender (or envelope-sender from)
254
             :external-format external-format
255
256
	     :ssl ssl
             :local-hostname (or local-hostname (usocket::get-host-name))))
Jan Idzikowski's avatar
Jan Idzikowski committed
257

Jan Idzikowski's avatar
Jan Idzikowski committed
258
259
260
261
(defun send-smtp (host from to subject message
                  &key ssl (port (if (eq :tls ssl) 465 25)) cc bcc
		  reply-to extra-headers html-message display-name
		  authentication attachments buffer-size
262
                  (local-hostname (usocket::get-host-name))
263
264
265
		  (envelope-sender from)
		  (external-format :utf-8))
  (with-smtp-mail (stream host envelope-sender (append to cc bcc)
Jan Idzikowski's avatar
Jan Idzikowski committed
266
267
268
                          :port port
                          :authentication authentication 
                          :ssl ssl
269
270
                          :local-hostname local-hostname
                          :external-format external-format)
271
272
273
274
275
276
277
278
    (write-rfc8822-message stream from to subject message 
                           :cc cc :reply-to reply-to 
                           :extra-headers extra-headers 
                           :html-message html-message
                           :display-name display-name
                           :attachments attachments 
                           :buffer-size buffer-size
                           :external-format external-format)))
Jan Idzikowski's avatar
Jan Idzikowski committed
279

Jan Idzikowski's avatar
Jan Idzikowski committed
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
(define-condition no-supported-authentication-method (smtp-error)
  ((features :initarg :features :reader features))
  (:report (lambda (condition stream)
             (print-unreadable-object (condition stream :type t)
               (format stream "SMTP authentication has been requested, but the SMTP server did not advertise any ~
                               supported authentication scheme.  Features announced: ~{~S~^, ~}"
                       (features condition))))))

(defun smtp-authenticate (stream authentication features)
  "Authenticate to the SMTP server connected on STREAM.
   AUTHENTICATION is a list of two or three elements.  If the first
   element is a keyword, it specifies the desired authentication
   method (:PLAIN or :LOGIN), which is currently ignored.  The actual
   method used is determined by looking at the advertised features of
   the SMTP server.  The (other) two elements of the AUTHENTICATION
   list are the login username and password.  FEATURES is the list of
   features announced by the SMTP server.

   If the server does not announce any compatible authentication scheme,
   the NO-SUPPORTED-AUTHENTICATION-METHOD error is signalled."
  (when (keywordp (car authentication))
    (pop authentication))
  (let ((server-authentication (loop for i in features
                                  for e = (search "AUTH " i :test #'equal)
                                  when (and e (= e 0))
                                  return i)))
    (destructuring-bind (username password) authentication
      (cond
        ((search " PLAIN" server-authentication :test #'equal)
         (smtp-command stream (format nil "AUTH PLAIN ~A" 
                                      (string-to-base64-string
                                       (format nil "~A~C~A~C~A" 
                                               username
                                               #\null username
314
                                               #\null password)
315
                                       :columns 0))
Jan Idzikowski's avatar
Jan Idzikowski committed
316
317
318
319
                       235))
        ((search " LOGIN" server-authentication :test #'equal)
         (smtp-command stream "AUTH LOGIN"
                       334)
320
         (smtp-command stream (string-to-base64-string username :columns 0)
Jan Idzikowski's avatar
Jan Idzikowski committed
321
                       334)
322
         (smtp-command stream (string-to-base64-string password :columns 0)
Jan Idzikowski's avatar
Jan Idzikowski committed
323
324
325
326
327
328
329
330
331
332
333
                       235))
        (t
         (error 'no-supported-authentication-method :features features))))))

(defun smtp-handshake (stream &key authentication ssl local-hostname)
  "Perform the initial SMTP handshake on STREAM.  Returns the stream
   to use further down in the conversation, which may be different from
   the original stream if we switched to SSL."

  (unless (or ssl authentication)
    ;; Unless we want ESMTP features, perform classic SMTP handshake and return
334
335
    ;; Read the initial greeting from the SMTP server
    (smtp-command stream nil 220)
Jan Idzikowski's avatar
Jan Idzikowski committed
336
    (smtp-command stream (format nil "HELO ~A" 
337
                                 (usocket::get-host-name))
Jan Idzikowski's avatar
Jan Idzikowski committed
338
339
340
341
                  250)
    (return-from smtp-handshake stream))

  ;; When SSL or authentication requested, perform ESMTP EHLO
Jan Idzikowski's avatar
Jan Idzikowski committed
342
343
  (let ((features)
        (flexi-external-format (flexi-streams:flexi-stream-external-format stream)))
Jan Idzikowski's avatar
Jan Idzikowski committed
344
    (labels
345
346
347
348
        ((read-greetings ()
	   ;; Read the initial greeting from the SMTP server
	   (smtp-command stream nil 220))
	 (do-ehlo ()
Jan Idzikowski's avatar
Jan Idzikowski committed
349
350
351
352
353
354
           (setf features (rest (smtp-command stream (format nil "EHLO ~A" local-hostname)
                                              250))))
         (convert-connection-to-ssl ()
           (setf stream 
                 #+allegro (socket:make-ssl-client-stream stream)
                 #-allegro
355
                 (let ((s (flexi-streams:flexi-stream-stream stream)))
Jan Idzikowski's avatar
Jan Idzikowski committed
356
                   (cl+ssl:make-ssl-client-stream 
357
                    (cl+ssl:stream-fd s)
Jan Idzikowski's avatar
Jan Idzikowski committed
358
359
360
361
                    :close-callback (lambda () (close s)))))
           #-allegro
           (setf stream (flexi-streams:make-flexi-stream 
                         stream
Jan Idzikowski's avatar
Jan Idzikowski committed
362
                         :external-format flexi-external-format))))
Jan Idzikowski's avatar
Jan Idzikowski committed
363
364
      (ecase ssl
        ((or t :starttls)
365
	 (read-greetings)
Jan Idzikowski's avatar
Jan Idzikowski committed
366
367
368
369
370
371
372
373
374
375
376
377
378
379
         (do-ehlo)
         (unless (find "STARTTLS" features :test #'equal)
           (error "this server does not supports TLS"))
         (print-debug "this server supports TLS")
         (smtp-command stream "STARTTLS"
                       220)
         (convert-connection-to-ssl)
         ;; After STARTTLS, the connection is "like new".  Re-do the
         ;; EHLO command to switch the server to ESMTP mode and read
         ;; the list of announced features again.
         (do-ehlo))
        (:tls
         ;; Plain SSL connection
         (convert-connection-to-ssl)
380
	 (read-greetings)
Jan Idzikowski's avatar
Jan Idzikowski committed
381
382
         (do-ehlo))
        ((nil)
383
	 (read-greetings)
Jan Idzikowski's avatar
Jan Idzikowski committed
384
385
386
         (do-ehlo))))
    (when authentication
      (smtp-authenticate stream authentication features)))
387
  stream)
388
  
389
(defun initiate-smtp-mail (stream envelope-sender to)
Jan Idzikowski's avatar
Jan Idzikowski committed
390
391
392
393
394
395
396
397
  "Initiate an SMTP MAIL command, sending a MAIL FROM command for the
   email address in FROM and RCPT commands for all receipients in TO,
   which is expected to be a list.

   If any of the TO addresses is not accepted, a RCPT-FAILED condition
   is signalled.  This condition may be handled by the caller in order
   to send the email anyway."
  (smtp-command stream 
398
                (format nil "MAIL FROM:<~A>" (substitute-return-newline envelope-sender))
Jan Idzikowski's avatar
Jan Idzikowski committed
399
400
401
                250)
  (dolist (address to)
    (restart-case 
402
403
        (smtp-command stream (format nil "RCPT TO:<~A>" 
                                     (substitute-return-newline address))
Jan Idzikowski's avatar
Jan Idzikowski committed
404
405
406
407
408
409
410
411
412
413
414
                      250
                      :condition-class 'rcpt-failed
                      :condition-arguments (list :recipient address))
      (ignore-recipient ())))
  (smtp-command stream "DATA"
                354))

(defun finish-smtp-mail (stream)
  "Finish sending an email to the SMTP server connected to on STREAM.
   The server is expected to be inside of the DATA SMTP command.  The
   connection is then terminated by sending a QUIT command."
415
  (write-to-smtp stream "")
Jan Idzikowski's avatar
Jan Idzikowski committed
416
417
418
419
420
  (smtp-command stream "." 250)
  (smtp-command stream "QUIT" 221))

(defun send-mail-headers (stream 
			  &key from to cc reply-to 
421
422
			  extra-headers display-name subject 
                          (external-format :utf-8))
Jan Idzikowski's avatar
Jan Idzikowski committed
423
424
425
  "Send email headers according to the given arguments to the SMTP
   server connected to on STREAM.  The server is expected to have
   previously accepted the DATA SMTP command."
426
  (write-to-smtp stream (format nil "Date: ~A" (get-email-date-string)))
427
428
  (if display-name
      (write-to-smtp stream (format nil "From: ~A <~A>" 
429
430
431
                                    (rfc2045-q-encode-string 
                                     display-name :external-format external-format)
                                    from))
432
      (write-to-smtp stream (format nil "From: ~A" from)))
433
  (write-to-smtp stream (format nil "To: ~{ ~a~^,~}" to))
434
  (when cc
435
    (write-to-smtp stream (format nil "Cc: ~{ ~a~^,~}" cc)))
436
437
438
  (write-to-smtp stream (format nil "Subject: ~A" 
                                (rfc2045-q-encode-string 
                                 subject :external-format external-format)))
439
  (write-to-smtp stream (format nil "X-Mailer: ~A" 
440
441
				(rfc2045-q-encode-string 
                                 *x-mailer* :external-format external-format)))
442
  (when reply-to
443
444
445
    (write-to-smtp stream (format nil "Reply-To: ~A" 
                                  (rfc2045-q-encode-string 
                                   reply-to :external-format external-format))))
446
447
448
  (when (and extra-headers
	     (listp extra-headers))
    (dolist (l extra-headers)
449
      (write-to-smtp stream 
450
		     (format nil "~A: ~{~a~^,~}" (car l) (rest l)))))
451
  (write-to-smtp stream "Mime-Version: 1.0"))
452

453
(defun send-multipart-headers (stream &key attachment-boundary html-boundary)
454
  (cond (attachment-boundary
455
	 (generate-multipart-header stream attachment-boundary 
456
457
				    :multipart-type "mixed"))
	(html-boundary (generate-multipart-header 
458
			stream html-boundary 
459
460
			:multipart-type "alternative"))
	(t nil)))
Jan Idzikowski's avatar
Jan Idzikowski committed
461

462
463
464
465
466
(defun write-rfc8822-message (stream from to subject message
                              &key cc reply-to extra-headers html-message 
                              display-name attachments buffer-size
                              (external-format :utf-8))
  (let* ((boundary (make-random-boundary))
467
468
469
         (message-transfer-encoding (when (string-has-non-ascii message)
                                      "quoted-printable"))
                                      
470
471
472
473
474
475
476
477
478
479
480
481
         (html-boundary (if (and attachments html-message)
                            (make-random-boundary)
                            boundary))
         (content-type 
          (format nil "text/plain; charset=~S" 
                  (string-upcase (symbol-name external-format)))))
    (send-mail-headers stream
                       :from from
                       :to to
                       :cc cc
                       :reply-to reply-to
                       :display-name display-name 
482
483
                       :extra-headers extra-headers :subject subject
                       :external-format external-format)
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
    (when (or attachments html-message)
      (send-multipart-headers stream
                              :attachment-boundary (when attachments boundary) 
                              :html-boundary html-boundary)
      (write-blank-line stream))
    ;;----------- Send  the body Message ---------------------------
    ;;--- Send the proper headers depending on plain-text, 
    ;;--- multi-part or html email 
    (cond ((and attachments html-message)
           ;; if both present, start attachment section, 
           ;; then define alternative section, 
           ;; then write alternative header
           (progn 
             (generate-message-header 
              stream :boundary boundary :include-blank-line? nil)
             (generate-multipart-header stream html-boundary 
                                        :multipart-type "alternative")
             (write-blank-line stream)
             (generate-message-header 
              stream :boundary html-boundary :content-type content-type 
504
              :content-transfer-encoding message-transfer-encoding
505
506
507
508
509
              :content-disposition "inline" :include-blank-line? nil)))
          (attachments 
           (generate-message-header 
            stream :boundary boundary 
            :content-type content-type :content-disposition "inline"
510
            :content-transfer-encoding message-transfer-encoding
511
512
513
514
            :include-blank-line? nil))
          (html-message
           (generate-message-header 
            stream :boundary html-boundary :content-type content-type 
515
            :content-transfer-encoding message-transfer-encoding
516
517
            :content-disposition "inline"))
          (t 
518
519
520
521
522
523
524
525
526
527
528
           (generate-message-header 
            stream :content-type content-type
            :content-transfer-encoding message-transfer-encoding
            :include-blank-line? nil)))
    (write-blank-line stream)
    (if message-transfer-encoding
        (progn
          (print-debug (format nil "to server body quoted-printable: ~A"
                               message))
          (rfc2045-q-encode-string-to-stream message stream 
                                             :external-format external-format))
529
        (mask-dot-stream message stream))
530
531
532
533
    (write-blank-line stream)
    (write-blank-line stream)
    ;;---------- Send  Html text if needed -------------------------
    (when html-message
534
535
536
537
538
539
540
541
542
543
544
545
546
547
      (let ((non-ascii-p (string-has-non-ascii html-message)))
        (generate-message-header 
         stream :boundary html-boundary 
         :content-type (format nil "text/html; charset=~S" 
                               (string-upcase (symbol-name external-format)))
         :content-transfer-encoding (when non-ascii-p "quoted-printable")
         :content-disposition "inline")
        (if non-ascii-p
            (progn
              (print-debug 
               (format nil "to server html-message quoted-printable: ~A"
                       html-message))
              (rfc2045-q-encode-string-to-stream 
               html-message stream :external-format external-format))
548
            (mask-dot-stream html-message stream))
549
        (send-end-marker stream html-boundary)))
550
551
552
553
554
555
556
    ;;---------- Send Attachments -----------------------------------
    (when attachments
      (dolist (attachment attachments)
        (send-attachment stream attachment boundary buffer-size 
                         external-format))
      (send-end-marker stream boundary))))

557
(defun write-to-smtp (stream command)
Jan Idzikowski's avatar
Jan Idzikowski committed
558
  (print-debug (format nil "to server: ~A" command)) 
559
  (write-sequence command stream)
560
561
562
  (write-char #\Return stream)
  (write-char #\NewLine stream)
  (force-output stream))
Jan Idzikowski's avatar
Jan Idzikowski committed
563

564
565
566
567
(defun write-blank-line (stream)
  (write-char #\Return stream)
  (write-char #\NewLine stream)
  (force-output stream))
568

569
570
571
(defun read-from-smtp (stream &optional lines)
  (let* ((line (read-line stream))
	 (response (string-trim '(#\Return #\NewLine) (subseq line 4)))
Jan Idzikowski's avatar
Jan Idzikowski committed
572
573
574
	 (response-code (parse-integer line :start 0 :junk-allowed t)))
    (print-debug (format nil "from server: ~A" line))
    (if (= (char-code (elt line 3)) (char-code #\-))
575
	(read-from-smtp stream (append lines (list response)))
Jan Idzikowski's avatar
Jan Idzikowski committed
576
	(values response-code response lines))))
577

Jan Idzikowski's avatar
Jan Idzikowski committed
578
579
580
581
582
583
584
585
586
(defun get-email-date-string ()
  (multiple-value-bind (sec min h d m y wd) (get-decoded-time)
    (let* ((month (elt '("Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec") (- m 1)))
	   (weekday (elt '("Mon" "Tue" "Wed" "Thu" "Fri" "Sat" "Sun") wd))
	   (timezone (get-timezone-from-integer
		      (- (encode-universal-time sec min h d m y 0)
			 (get-universal-time)))))
      (format nil "~A, ~2,'0d ~A ~d ~2,'0d:~2,'0d:~2,'0d ~D" 
	      weekday d month y h min sec timezone))))
587

Jan Idzikowski's avatar
Jan Idzikowski committed
588
589
590
591
(defun get-timezone-from-integer (x)
  (let ((min (/ x 60))
	(hour (/ x 3600)))
    (if (integerp hour)
Jan Idzikowski's avatar
Jan Idzikowski committed
592
        (cond
Jan Idzikowski's avatar
Jan Idzikowski committed
593
594
595
	  ((>= hour 0)
	   (format nil "+~2,'0d00" hour))
	  ((< hour 0)
Jan Idzikowski's avatar
Jan Idzikowski committed
596
597
598
          (format nil "-~2,'0d00" (* -1 hour))))
        (multiple-value-bind (h m) (truncate min 60)
          (cond
Jan Idzikowski's avatar
Jan Idzikowski committed
599
600
601
602
	  ((>= hour 0)
	   (format nil "+~2,'0d~2,'0d" h (truncate m)))
	  ((< hour 0)
	   (format nil "-~2,'0d~2,'0d" (* -1 h) (* -1 (truncate m)))))))))