skip to Main Content

I have been trying to make the content or message body to appear in the emails but it doesn’t appear to be working. It’s mentioned that a empty line is needed before the message and with new line after subject. Also, each time I run the script it runs but gives this error "Task timed out after 3.01 seconds" but I get the email, however, the Lambda function is marked as Failed…not sure why?? Maybe that’s not so much of a big deal but if it ran then I’m assuming it was successful which is confusing since it says failed. The biggest thing here is the content not showing up. Thank you for any assistance.

import smtplib
            
sender = 'example.org'
recipient = contact


        try:
            subject = str(instance_name) + ' Issues'
            content="Hello World" 
            mail = smtplib.SMTP('smtp.office365.com', 587)
            mail.ehlo()
            mail.starttls()
            mail.login('example.org','1234567890')
            header = 'To:' + recipient + 'n' + 'From:' 
            +sender+'n'+'subject:' + subject  + 'n'
            content=header+content
            mail.sendmail(sender, recipient, content)
         

        except:
            print ("Error: unable to send email")

2

Answers


  1. Chosen as BEST ANSWER

    I changed this line of code "+sender+'n'+'subject:' + subject + 'nn' " and it appears to be working. As far as the timeout issue. I increased it to a minute and it works fine now.


  2. This works perfectly for me, I hope it will help you out.

    import os
    import socket
    import smtplib
    from email.message import EmailMessage
    from email.message import EmailMessage
    
    
    message = EmailMessage()
    
    # Recepients addresses in a list
    message['To']=["[email protected]","[email protected]"]
    message['Cc'] = ["[email protected]"]
    message['Bcc'] = ["[email protected]"]
    message['From'] = "[email protected]"
    message['Subject'] = "Subject Matter"
    message.set_content("I received the data you sent.")
    
    
    # Attach a document.
    with open("document.txt", "rb") as file:
        message.add_attachment(file.read(), maintype="application", subtype="octet-stream",
                                filename=os.path.basename(file.name))
        print(f'Document: {os.path.basename(file.name)} attached successfully.')
        
    # Login in and send your email.
    try:
        with smtplib.SMTP_SSL("smtp.office365.com", 587) as smtp:
            smtp.login('[email protected]', 'password')
            print('Sending email...')
            smtp.send_message(message)
            print(f'Email successfully sent.')
            smtp.quit()
    except (smtplib.SMTPRecipientsRefused, socket.gaierror):
        print ("Error: unable to send email")
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search