Outlook email Error

1833
4
Jump to solution
10-04-2021 12:48 PM
JamesStout101
New Contributor II

Error:

Traceback (most recent call last): File "C:\Python27\ArcGIS10.6\Lib\site-packages\Pythonwin\pywin\framework\scriptutils.py", line 326, in RunScript exec codeObject in __main__.__dict__ File "C:\Users\jstout\Desktop\PY\ESRI1.py", line 37, in <module> server.sendmail(FROM, TO, MESSAGE) File "C:\Python27\ArcGIS10.6\lib\smtplib.py", line 742, in sendmail (code, resp) = self.rcpt(each, rcpt_options) File "C:\Python27\ArcGIS10.6\lib\smtplib.py", line 490, in rcpt return self.getreply() File "C:\Python27\ArcGIS10.6\lib\smtplib.py", line 369, in getreply raise SMTPServerDisconnected("Connection unexpectedly closed") SMTPServerDisconnected: Connection unexpectedly closed

My Code

import arcpy, arceditor, time, smtplib

# Set the workspace
arcpy.env.workspace = r'C:\Users\jstout\AppData\Roaming\ESRI\Desktop10.6\ArcCatalog\EED_FM@SDE.sde'

# Set a variable for the workspace
adminConn = arcpy.env.workspace

# Get a list of connected users.
userList = arcpy.ListUsers(adminConn)
print "User List Finished"

# Get a list of user names of users currently connected and make email addresses
emailList = [user.Name + "@cityofelizabethton.org" for user in arcpy.ListUsers(adminConn)]
print "Email List Finished"

# Take the email list and use it to send an email to connected users.

SERVER = "cityofelizabethton-org.mail.protection.outlook.com"
FROM = "SDE Admin <jstout@cityofelizabethton.org>"
TO = emailList
SUBJECT = "Maintenance is about to be performed"
MSG = "Auto generated Message.\n\rServer maintenance will be performed in 15 minutes. Please log off."

# Prepare actual message
MESSAGE = """\
From: %s
To: %s
Subject: %s

%s
""" % (FROM, ", ".join(TO), SUBJECT, MSG)
print(MESSAGE)

# Send the mail
server = smtplib.SMTP(SERVER)
server.sendmail(FROM, TO, MESSAGE)
server.quit()
print "Email sent"

# Block new connections to the database.
# print("The database is no longer accepting connections")
# arcpy.AcceptConnections(adminConn, False)

# Disconnect all users from the database.
# print("Disconnecting all users")
# arcpy.DisconnectUser(adminConn, "ALL")

# This portion is to call a C# executable to call orphaned version cleanup.
print "Start EED Automated Cleanup"
import os
os.startfile(r"C:\Users\jstout\Desktop\EED_Automated_Cleanup\bin\x86\Debug\AutomatedCleanup.exe")
import sys, string, os, arcgisscripting
import subprocess
subprocess.Popen([r"C:\Users\jstout\Desktop\EED_Automated_Cleanup\bin\x86\Debug\AutomatedCleanup.exe"])
print "Automated Cleanup finished"

# Wait .5 minutes
time.sleep(30)

database = "Database Connections/toolboxDEFAULTVersion.sde"
versions = arcpy.ListVersions(adminConn)

# Print the versions available to the user
for version in versions:
print(version)
print "Version list complete."

# Execute the ReconcileVersions tool.
# Use a list comprehension to get a list of version names where the owner
# is the current user and make sure sde.default is not selected.
print 'Reconcile versions started.'

verList = [ver.name for ver in arcpy.da.ListVersions() if ver.isOwner
== True and ver.name.lower() != 'sde.EFAULT']

arcpy.ReconcileVersions_management(adminConn, "ALL_VERSIONS", "SDE.DEFAULT", "", "LOCK_ACQUIRED", "NO_ABORT", "BY_OBJECT", "FAVOR_TARGET_VERSION", "POST","DELETE_VERSION")

# Write messages to a Text File
txtFile = open("c:\\temp\\GPMessages.txt","w")
txtFile.write (arcpy.GetMessages())
txtFile.close()

print ('see error log at "c:\temp\GPMessages.txt"')
print'Reconciling Complete'

# Run the compress tool.
print("Running compress")
arcpy.Compress_management(adminConn)

# Use a connection file to create the connection
print "Check state ID"
egdb = r'C:\Users\jstout\AppData\Roaming\ESRI\Desktop10.6\ArcCatalog\EED_FM@SDE.sde'
egdb_conn = arcpy.ArcSDESQLExecute(egdb)

table_name = 'EED_FM.sde.sde_States'
field_name = 'state_id'

sql = '''
SELECT {0}, COUNT({0}) AS f_count FROM {1}
GROUP BY {0}
ORDER BY f_count DESC
'''.format(field_name, table_name)

egdb_return = egdb_conn.execute(sql)
for i in egdb_return:
print('{}: {}'.format(*i))
print "State count complete"

# Allow the database to begin accepting connections again
# arcpy.AcceptConnections(adminConn, True)
# print "allow connections to database"

# Update statistics and indexes for the system tables
# Note: to use the "SYSTEM" option the user must be an geodatabase or database administrator.
# Rebuild indexes on the system tables
print("Rebuilding indexes on the system tables")
arcpy.RebuildIndexes_management(adminConn, "SYSTEM")

# Update statistics on the system tables
print("Updating statistics on the system tables")
arcpy.AnalyzeDatasets_management(adminConn, "SYSTEM")

print("Finished.")

0 Kudos
2 Solutions

Accepted Solutions
JamesStout101
New Contributor II

If i have a server error I don't know how to remedy that.

My user list has admin connections in it as well as user connections don't know how to remove the admin user names from the user list. The admins have no email.

Example, SDE, DBO, ARCFM, RESPONDER, non admin users all have emails admins do not.

View solution in original post

0 Kudos
BlakeTerhune
MVP Regular Contributor

You may need to find an Outlook email administrator that supports your organization to troubleshoot a server error.

Our organization has a separate database that stores the email addresses of our normal users with user name so I just query that database with the connected user names from ArcGIS and send the email to every address that was actually returned. Since there are no org domain users like "SDE" or "DBO", there are no email addresses returned from the query.

How are you getting your email addresses?

View solution in original post

4 Replies
DavidPike
MVP Frequent Contributor

Looks like your SMTP relay is bouncing you out, has it worked before? have you got the right credentials if it's secured?

I'd advise forgetting about the rest of the code when posting and testing the issue, if the rest of the code works, it's just gets in the way in terms of troubleshooting the emailer.

Also, possibly StackOverflow would be a better place.

0 Kudos
BlakeTerhune
MVP Regular Contributor

Not sure exactly what that error might be referring to. Just for another thing to try, here's the email function I built based on examples in the Python docs

def sendEmail(subject="", body_content="", to=[], cc=[], bcc=[], from_addr="donotreply@mydomain.suffix"):
    """Send a plain text email.

    Required imports:
        from email.message import EmailMessage # for a text/plain email message
        import smtplib # for sending email

    :param str subject: Subject line of email.
    :param str body_content: Main message in the body of the email.
    :param list to: A list of email addresses as strings for sending the email to.
    :param list cc: A list of email addresses as strings for CC'ing the email.
    :param list bcc: A list of email addresses as strings for BCC'ing the email.
    :param str from_addr: The email address from which to send the email.
    :return: All email addresses that received the email (to, cc, bcc).
    :rtype: Dictionary
    """
    from email.message import EmailMessage
    import smtplib
    # Validate email recipient args
    for recipient in [to, cc, bcc]:
        if not isinstance(recipient, list):
            raise TypeError(f"Recipients (to, cc, bcc) must each be a list of strings; not {type(recipient)}")
    # Create email message object and content.
    msg = EmailMessage()
    msg.set_content(body_content)
    # Set recipients
    msg["Subject"] = subject
    msg["From"] = from_addr
    msg["To"] = ", ".join(to)
    msg["Cc"] = ", ".join(cc)
    msg["Bcc"] = ", ".join(bcc)
    # Send the message via our own SMTP server.
    with smtplib.SMTP("mymailserver.mydomain.suffix") as smtp:
        smtp.send_message(msg)
    print("sendEmail() successful")
    return {"to": to, "cc": cc, "bcc": bcc}

 

Like @DavidPike mentioned, there's likely something your email server isn't happy with and the GeoNet community probably can't help much with that.

0 Kudos
JamesStout101
New Contributor II

If i have a server error I don't know how to remedy that.

My user list has admin connections in it as well as user connections don't know how to remove the admin user names from the user list. The admins have no email.

Example, SDE, DBO, ARCFM, RESPONDER, non admin users all have emails admins do not.

0 Kudos
BlakeTerhune
MVP Regular Contributor

You may need to find an Outlook email administrator that supports your organization to troubleshoot a server error.

Our organization has a separate database that stores the email addresses of our normal users with user name so I just query that database with the connected user names from ArcGIS and send the email to every address that was actually returned. Since there are no org domain users like "SDE" or "DBO", there are no email addresses returned from the query.

How are you getting your email addresses?