pythonpython-3.xyahoo-mail

Correct format for IMAP append command in Python? (Yahoo mail)


The following Python function works for outlook, gmail and my shared hosting exim server but when sending mail through yahoo.com it returns this error:

APPEND command error: BAD ['[CLIENTBUG] Additional arguments found after last expected argument']. Data: FHDJ4 APPEND inbox.sent "31-Aug-2016 12:30:45 +0100" {155}

For comparison, outlook returns:

('OK', ['[APPENDUID 105 2] APPEND completed.'])

Gmail returns:

 ('OK', ['[APPENDUID 14 2] (Success)'])

and Exim returns:

('OK', ['[APPENDUID 1472211409 44] Append completed (0.788 + 0.076 secs).'])

My function uses imaplib2, the arguments passed to it are all strings, and self.username is the sending email address as address@domain.com

My function is:

def send_mail(self, to_addrs, subject, msgtext, verbose=False):
    # build message to send
    msg = email.message.Message()
    msg.set_unixfrom('pymotw')
    msg['From'] = self.username
    msg['To'] = to_addrs
    msg['Subject'] = subject
    msg.set_payload(msgtext)

    if verbose: print("Sending Mail:\n ", msg)

    # connect and send message
    server = self.connect_smtp()
    server.ehlo()
    server.login(self.username, self.password)
    server.sendmail(self.username, to_addrs, str(msg))
    server.quit()
    print("Saving mail to sent")
    sentbox_connection = self.imap_connection
    print(sentbox_connection.select('inbox.sent'))
    print(sentbox_connection.append('inbox.sent', None, imaplib2.Time2Internaldate(time.time()) , str(msg)))

I've tried generating the msg variable with this line instead:

        msg = "From: %s\r\n" % self.username + "To: %s\r\n" % to_addrs + "Subject: %s\r\n" % subject + "\r\n" + msgtext

and appending the message using "" instead of None like so:

        print(sentbox_connection.append('inbox.sent', None, imaplib2.Time2Internaldate(time.time()) , str(msg)))

Can you tell me what I'm doing wrong? Or if Yahoo has a specific way of handling append commands that I need to account for?

Edit: To clarify, sending the mail works OK for all smtp servers, but appending the sent mail to inbox.sent fails for yahoo


Solution

  • I've resolved this. I noticed the message text did not end with CRLF. Other mail servers were appending this serverside to accept the command, Yahoo does not. The below now works.

    I've amended the message payload line to: msg.set_payload("%s \r\n" % msgtext) # Yahoo is strict with CRLF at end of IMAP command