Python Forum
Python error - how do I fix it?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python error - how do I fix it?
#1
import smtplib
import email
import os
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email import encoders
from email.message import Message
from email.mime.base import MIMEBase




g_strPath = "C:\\Users\\gregaryb\\Documents\\GitHub\\boylesg.github.io\\FindATradie\\data\\"




def CreateEmailImage(strImageFilename, strImageID):
    fileImage = open(strImageFilename, 'rb')
    MsgImage = MIMEImage(fileImage.read())
    fileImage.close()

    # Define the image's ID as referenced above
    MsgImage.add_header("Content-ID", "<" + strImageID + ">")
    return MsgImage




def DoSendEmail(strEmail):
    strFromEmail = "[email protected]"
    RootEmailMsg = MIMEMultipart('related')
    RootEmailMsg["Subject"] = "NEW SERVICE for tradies: find-a-tradie.com.au"
    RootEmailMsg['From'] = strFromEmail
    RootEmailMsg['To'] = strEmail
    RootEmailMsg.preamble = 'This is a multi-part message in MIME format.'

    EmailMsgAlternative = MIMEMultipart('alternative')

    strText = "This is the alternative plain text message."
    TextEmailMsg = MIMEText(strText)
    EmailMsgAlternative.attach(TextEmailMsg)

    strText = "<!DOCTYPE html>\n"
    "    <html>\n"
    "        <head>\n"
    "            <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n"
    "            <title>https://www.find-a-tradie.com.au</title>\n"
    "        </head>\n"
    "        <body>\n"
    "        <p><a href=\"https://www.find-a-tradie.com.au\" class=\"moz-txt-link-freetext\">https://www.find-a-tradie.com.au</a></p>\n"
    "        <p><img src=\"cid:home_page\" alt="" width=\"455\" height=\"183\"></p>\n"
    "        <p>Find-a-Tradie is a new advertising web service form Australian small tradie businesses. It has been created by an Australian small business tradie FOR Australian tradies.<br></p>\n"
    "        <p>It is ideal for small businesses that are just starting out and don't have a large advertising budget.</p>\n"
    "        <p>Or for small businesses in trades that typically involve many small low value jobs such as gardening, lawn mowing, pet care and domestic cleaning.<br></p>\n"
    "        <p>Unlike HiPages, ServiceSeeking and OneFlare we do not charge you to obtain customer contact details - you can obtain them for free.</p>\n"
    "        <p>We only charge you a flat annual membership fee of $10 per month or $120 per year.</p>\n"
    "        <p>For that you can try for as many jobs as you want - there is no limit.</p>\n"
    "        <p>However every new tradie gets their first 6 months of membership for free, and this offer is permanent.</p>\n"
    "        <p>So tradie can 'try before they buy'.<br></p>\n"
    "        <p>Customers can join for FREE at all times.<br></p>\n"
    "        <p>------------------------------------------------------------------------------------------------------------------------------------<br></p>\n"
    "        <p> The service uses a feedback based mutual trust system similar to eBay.&nbsp; </p>\n"
    "        <p><img src=\"cid:feedback\" width=\"1077\" height=\"386\"></p>\n"
    "        <p>So tradies can ALSO check the feedback history of clients before deciding to do any jobs for them.</p>\n"
    "        <p><img src=\"cid:feedback_history\" width=\"1081\" height=\"414\"></p>\n"
    "        <p>As well as clients being able to check the feedback history of tradies.<br>\n"
    "        <img src=\"cid:feedback_as\" width=\"1079\" height=\"414\"><br>\n"
    "        <p>So give it a try - remember your first 6 months is free. Get started today! Register now!</p><br>\n"
    "        <p><br></p>\n"
    "    </body>\n"
    "</html>\n"
    TextEmailMsg = MIMEText(strText)
    EmailMsgAlternative.attach(strText)

    RootEmailMsg.attach(EmailMsgAlternative)
    RootEmailMsg.attach(CreateEmailImage(g_strPath + "home_page.jpg", "home_page"))
    RootEmailMsg.attach(CreateEmailImage(g_strPath + "feedback.jpg", "feedback"))
    RootEmailMsg.attach(CreateEmailImage(g_strPath + "customer_feedback.jpg", "customer_feedback"))
    RootEmailMsg.attach(CreateEmailImage(g_strPath + "tradie_feedback.jpg", "tradie_feedback"))

    # Send the email via our own SMTP server.
    SMTPObject = smtplib.SMTP("smtp-mail.outlook.com", 587)
    #SMTPObject.connect("smtp.office365.com", 993)
    SMTPObject.ehlo()
    SMTPObject.starttls()
    SMTPObject.ehlo()
    SMTPObject.login("[email protected]", "Pulsar112358#")
    SMTPObject.sendmail(strFromEmail, strEmail, RootEmailMsg.as_string())
    SMTPObject.quit()





strMsg = ""
g_arrayEmailFiles = ["ARBORISTS.email",
                   "CLEANERS.email",
                   "CONCRETERS.email",
                   "ELECTRICIANS.email",
                   "GARDENERS.email",
                   "PAINTERS.email",
                   "PET CARERS.email",
                   "PLUMBERS.email"]

for strEmailFile in g_arrayEmailFiles:
    nFileSize = os.path.getsize(g_strPath + strEmailFile)
    if (nFileSize > 0):
        fileEmail = open(g_strPath + strEmailFile, "r")
        print("Processing email file " + strEmailFile + "...")
        while True:
            nLine = 0
            while (True):
                strEmail = fileEmail.readline()
                nLine += 1
                if (len(strEmail) > 0):
                    print("Sending email to " + strEmail + "...")
                    DoSendEmail(strEmail)
                    sleep(30)
                else:
                    break;
            file.close()
            print("\n---------------------------------\n")
The call to RootEmailMsg.as_string() in SMTPObject.sendmail(strFromEmail, strEmail, RootEmailMsg.as_string()) causes this error:


Traceback (most recent call last):
Error:
File "C:\Program Files\JetBrains\PyCharm Community Edition 2023.3.3\plugins\python-ce\helpers\pydev\pydevd.py", line 1534, in _exec pydev_imports.execfile(file, globals, locals) # execute the script ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\JetBrains\PyCharm Community Edition 2023.3.3\plugins\python-ce\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile exec(compile(contents+"\n", file, 'exec'), glob, loc) File "C:\Users\gregaryb\Documents\GitHub\boylesg.github.io\PythonProject\.venv\Scripts\SendEmails.py", line 119, in <module> DoSendEmail(strEmail) File "C:\Users\gregaryb\Documents\GitHub\boylesg.github.io\PythonProject\.venv\Scripts\SendEmails.py", line 90, in DoSendEmail SMTPObject.sendmail(strFromEmail, strEmail, RootEmailMsg.as_string()) ^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\gregaryb\AppData\Local\Programs\Python\Python312\Lib\email\message.py", line 188, in as_string g.flatten(self, unixfrom=unixfrom) File "C:\Users\gregaryb\AppData\Local\Programs\Python\Python312\Lib\email\generator.py", line 115, in flatten self._write(msg) File "C:\Users\gregaryb\AppData\Local\Programs\Python\Python312\Lib\email\generator.py", line 180, in _write self._dispatch(msg) File "C:\Users\gregaryb\AppData\Local\Programs\Python\Python312\Lib\email\generator.py", line 217, in _dispatch meth(msg) File "C:\Users\gregaryb\AppData\Local\Programs\Python\Python312\Lib\email\generator.py", line 275, in _handle_multipart g.flatten(part, unixfrom=False, linesep=self._NL) File "C:\Users\gregaryb\AppData\Local\Programs\Python\Python312\Lib\email\generator.py", line 115, in flatten self._write(msg) File "C:\Users\gregaryb\AppData\Local\Programs\Python\Python312\Lib\email\generator.py", line 180, in _write self._dispatch(msg) File "C:\Users\gregaryb\AppData\Local\Programs\Python\Python312\Lib\email\generator.py", line 217, in _dispatch meth(msg) File "C:\Users\gregaryb\AppData\Local\Programs\Python\Python312\Lib\email\generator.py", line 275, in _handle_multipart g.flatten(part, unixfrom=False, linesep=self._NL) File "C:\Users\gregaryb\AppData\Local\Programs\Python\Python312\Lib\email\generator.py", line 106, in flatten old_msg_policy = msg.policy ^^^^^^^^^^ AttributeError: 'str' object has no attribute 'policy'
deanhystad write Aug-13-2024, 04:33 PM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Reply
#2
Why are you using email.mime instead of email.contentmanager?

https://docs.python.org/3/library/email.html
Reply
#3
(Aug-13-2024, 06:00 PM)deanhystad Wrote: Why are you using email.mime instead of email.contentmanager?

https://docs.python.org/3/library/email.html

For no other reason that that was the sample code I happened to find Wink
Reply
#4
(Aug-13-2024, 06:00 PM)deanhystad Wrote: Why are you using email.mime instead of email.contentmanager?

https://docs.python.org/3/library/email.html

BRILLIANT! I can send an email.....thank you very much Smile

However there is one issue still remaining - my html is not being rendered. This is what the email looks like in Thunderbird email client:

   

So what am I still doing wrong?

def DoSendEmail(strToEmail):
    strFromEmail = "[email protected]"

    # Create the base text message.
    msg = EmailMessage()
    msg['Subject'] = "NEW SERVICE for tradies: find-a-tradie.com.au"
    msg['From'] = Address("Find a Tradie", "find-a-tradie", "outlook.com")
    strToEmail = strToEmail.replace("\n", "")
    arrayParts = strToEmail.split("@")
    msg['To'] = Address("Fellow Tradie", arrayParts[0], arrayParts[1])
    msg.set_content("""\
            Find-a-tradie.com.au is a new advertising web service form Australian small tradie businesses. It has 
            been created by an Australian small business tradie FOR Australian tradies.\n\n
            It is ideal for small businesses that are just starting out and don't have a large advertising budget.\n\n
            Or for small businesses in trades that typically involve many small low value jobs such as gardening, 
            lawn mowing, pet care and domestic cleaning.\n\n
            Unlike HiPages, ServiceSeeking and OneFlare we do not charge you to obtain customer contact details - 
            you can obtain them for free.\n\n
            We only charge you a flat annual membership fee of $10 per month or $120 per year.\n\n
            For that you can try for as many jobs as you want - there is no limit.\n\n
            However every new tradie gets their first 6 months of membership for free, and this offer is permanent.\n\n
            So tradie can 'try before they buy'.\n\n
            Customers can join for FREE at all times.\n\n
            The service uses a feedback based mutual trust system similar to eBay.\n\n
            So tradies can ALSO check the feedback history of clients before deciding to do any jobs for them, in 
            addition to clients being able to check the feedback history of tradies.\n\n
            So give it a try - remember your first 6 months is free. Get started today! Register now!
            """)

    # Add the html version.  This converts the message into a multipart/alternative
    # container, with the original text message as the first part and the new html
    # message as the second part.
    strCIDHomePage = make_msgid("home", "page")
    strCIDFeedback = make_msgid("feedback", "trust")
    strCIDCustomerFeedback = make_msgid("customer", "feedback")
    strCIDTradieFeedback = make_msgid("tradie", "feedback")

    msg.add_alternative("""\
    <!DOCTYPE html>\n
    <html>\n
        <head>\n
            <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n
            <title>https://www.find-a-tradie.com.au</title>\n
        </head>\n
        <body>\n
            <p><a href=\"https://www.find-a-tradie.com.au\" class=\"moz-txt-link-freetext\">https://www.find-a-tradie.com.au</a></p>\n
            <p><img src=\"cid:{strCIDHomePage}\" alt="" width=\"455\" height=\"183\"></p>\n
            <p>Find-a-tradie.com.au is a new advertising web service form Australian small tradie businesses. It has been created by an Australian small business tradie FOR Australian tradies.<br></p>\n
            <p>It is ideal for small businesses that are just starting out and don't have a large advertising budget.</p>\n
            <p>Or for small businesses in trades that typically involve many small low value jobs such as gardening, lawn mowing, pet care and domestic cleaning.<br></p>\n
            <p>Unlike HiPages, ServiceSeeking and OneFlare we do not charge you to obtain customer contact details - you can obtain them for free.</p>\n
            <p>We only charge you a flat annual membership fee of $10 per month or $120 per year.</p>\n
            <p>For that you can try for as many jobs as you want - there is no limit.</p>\n
            <p>However every new tradie gets their first 6 months of membership for free, and this offer is permanent.</p>\n
            <p>So tradie can 'try before they buy'.<br></p>\n
            <p>Customers can join for FREE at all times.<br></p>\n
            <p>------------------------------------------------------------------------------------------------------------------------------------<br></p>\n
            <p> The service uses a feedback based mutual trust system similar to eBay.&nbsp; </p>\n
            <p><img src=\"cid:{strCIDFeedback}\" width=\"1077\" height=\"386\"></p>\n
            <p>So tradies can ALSO check the feedback history of clients before deciding to do any jobs for them.</p>\n
            <p><img src=\"cid:{strCIDCustomerFeedback}\" width=\"1081\" height=\"414\"></p>\n
            <p>As well as clients being able to check the feedback history of tradies.<br>\n
            <img src=\"cid:{strCIDTradieFeedback}\" width=\"1079\" height=\"414\"><br>\n
            <p>So give it a try - remember your first 6 months is free. Get started today! Register now!</p><br>\n
            <p><br></p>\n
        </body>\n
    </html>\n
    """.format(strCIDHomePage=strCIDHomePage[1:-1], strCIDFeedback=strCIDFeedback[1:-1],
            strCIDCustomerFeedback=strCIDCustomerFeedback[1:-1], strCIDTradieFeedback=strCIDTradieFeedback[1:-1],
            subtype='html'))
    # NOTE: we needed to peel the <> off the msgid for use in the html.

    # Now add the related image to the html part.
    with open(g_strPath + "home_page.jpg", 'rb') as img:
        msg.get_payload()[1].add_related(img.read(), 'image', 'jpeg',
                                         cid=strCIDHomePage)
    with open(g_strPath + "feedback.jpg", 'rb') as img:
        msg.get_payload()[1].add_related(img.read(), 'image', 'jpeg',
                                         cid=strCIDFeedback)
    with open(g_strPath + "customer_feedback.jpg", 'rb') as img:
        msg.get_payload()[1].add_related(img.read(), 'image', 'jpeg',
                                         cid=strCIDCustomerFeedback)
    with open(g_strPath + "tradie_feedback.jpg", 'rb') as img:
        msg.get_payload()[1].add_related(img.read(), 'image', 'jpeg',
                                         cid=strCIDTradieFeedback)

    # Send the email via our own SMTP server.
    SMTPObject = smtplib.SMTP("smtp-mail.outlook.com", 587)
    #SMTPObject.connect("smtp.office365.com", 993)
    SMTPObject.ehlo()
    SMTPObject.starttls()
    SMTPObject.ehlo()
    SMTPObject.login("[email protected]", "Pulsar112358#")
    SMTPObject.send_message(msg)
    SMTPObject.quit()
Reply
#5
This looks like a nice, short tutorial.

https://betterdatascience.com/send-emails-with-python/
Reply
#6
The standar email
(Aug-14-2024, 04:24 AM)gregaryb Wrote: However there is one issue still remaining - my html is not being rendered.
A advice the standard library email stuff can be difficult and messy,so use yagmail📬
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020