0

When sending large count email response this error 554, Transaction failed: Duplicate header subject. I'm use smtplib + aws SES. For all messages, the header must be the same. How can I fix this error? If send message without subject, all working.

import smtplib
import json


from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

args = []
msg  = MIMEMultipart('alternative')
msg['From'] = 'noreply@example.com'
html = open('mail.html').read()


EMAIL_HOST = 'email-smtp...'
EMAIL_HOST_USER = 'sss'
EMAIL_HOST_PASSWORD = 'ssssss'
EMAIL_PORT = 587

def lambda_handler(event, context):
    body = event['Records'][0]['Sns']['Message']
    global args
    args = json.loads(body)['args']
    set_worker(json.loads(body)['method'])()

    return 'success'


def set_worker(method):
    return {
                'email'           : email
            }.get(method, 'Not found')


def email():
    global msg, html

    name = args[0]
    title          = args[1]
    msg_body       = args[2]
    email          = args[3]
    url            = args[4]
    subject        = "Test"

    msg['Subject'] = subject
    msg['To'] = email

    html = html.format(title, community_name, title, msg_body, community_name)
    mime_text = MIMEText(html, 'html')
    msg.attach(mime_text)
    send_message()

def send_message():
    mail = smtplib.SMTP(EMAIL_HOST, EMAIL_PORT)
    mail.ehlo()
    mail.starttls()
    mail.login(EMAIL_HOST_USER, EMAIL_HOST_PASSWORD)
    mail.sendmail(msg['From'], msg['To'], msg.as_string())
PaulG
  • 13,871
  • 9
  • 56
  • 78
Andy
  • 863
  • 1
  • 8
  • 20
  • The issue is multiple messages with the same subject... it's two subject headers on one single message. Examine the results of `msg.as_string()` and it should become apparent exactly what's happening. – Michael - sqlbot Mar 17 '17 at 01:25
  • @michael-sqlbot Could you please elaborate on it? – Andy Mar 17 '17 at 04:33
  • Log the value that `msg.as_string()` returns. It's an email message fully formed and ready to be sent out over the wire, with headers and a body, the same thing you see when looking at a message in Gmail and you click "Show Original" -- the low-level representation of the message in the format used for transmission. The error seems to suggest that the email headers contain two `Subject:` lines instead of just one, which would be wrong. Edit the output of `msg.as_string()` of a failing email into the question. – Michael - sqlbot Mar 17 '17 at 10:27

1 Answers1

0

When working with aws-lambda cannot be used global variables . The error was in the fact that duplicate messages were written to the variable msg.

Andy
  • 863
  • 1
  • 8
  • 20