pythonpython-2.7amazon-sessmtplib

How to fixed "554, Transaction failed: Duplicate header 'Subject' "?


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())

Solution

  • 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.