Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
SMTPlib help
#1
Hello, I'm stuck at this point and looking for some help. I am trying to get the text file that my script creates, then email that out as an attached file. I keep getting an error "ERROR (421, b'4.3.2 Service not available')" my server is whitelisted to the mail relay server which I verified already.

Here is my code, please let me know what and where I am doing wrong this has been driving me crazy for 2 days now. ( i removed my email from and to list along with any info that would identify my mail server for security reasons)

#! /usr/bin/python3.6
import pymysql
import datetime
from pncnetworkdata import *
from datetime import datetime
import logging
import smtplib
from email.message import EmailMessage


logger = logging.getLogger('pncnetwork')
hdlr = logging.FileHandler('/opt/scripts/errors/pncnetworkerrors.log')
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr) 
logger.setLevel(logging.WARNING)
#logging.info('Started')



try:
    markets = ["Beltway", "Keystone", "Freedom", "New England"]
    count = 0
    cursorRowCount = 0
    recordPrint = ""
    for HOST in HOSTS:
        db_con = pymysql.connect(host=HOST, port=3306, user=USERNAME, passwd=PASSWORD, db=DATABASE) 
        sql_select_Query = "SELECT * FROM pncnetwork where id=(SELECT MAX(id) FROM pncnetwork)"


        cursor = db_con.cursor()
        cursor.execute(sql_select_Query)
        records = cursor.fetchall()
        for row in records:
            recordPrint += markets[count] + ', ' + str(row[2]) + "\n" 
        cursorRowCount += cursor.rowcount
        count += 1
        db_con.close()
#    print ("Total number of rows in pncnetwork is: ", cursorRowCount)
    print ("\nPrinting each pncnetwork record\n", recordPrint)



# This section will print the script to file using the current date and save it to /opt/scripts/output


    def get_filename_datetime():
    # Use current date to get a text file name.
     return "PNCChecker-" + str(datetime.today().replace(second=0, microsecond=0)) + ".txt"

#Get full path for writing 
    name = get_filename_datetime()
    print("NAME", name)

    path = "/opt/scripts/output/" + name
    print("PATH", path);

    with open(path, "w") as f:
    # Write Data to file
     f.write (recordPrint)


     msg = EmailMessage()
     msg["From"] = 'removed my email'
     msg["Subject"] = "PNC Checker Results"
     msg["To"] = 'removed to list'
     msg.set_content("Hello, Please see attached results from today's PNC Checker script.")
     msg.add_attachment(open(path, "r").read(), filename="NAME")
     
     s = smtplib.SMTP('mailrelay.someone.com')
     s.send_message(msg)

except Exception as e:
    print("ERROR ", str(e))
    logger.error('message')
Reply
#2
Please post the complete, unaltered error traceback.
It contains valuable information, showing what leads up to the actual error.
Reply
#3
(Apr-27-2020, 10:56 PM)Larz60+ Wrote: Please post the complete, unaltered error traceback.
It contains valuable information, showing what leads up to the actual error.

Hello please Here is the error from the script being ran. I did verify that my server is whitelisted and I was able to send a test mail from the server to myself.

tpolim001@srv01 ~]$ ./pncnetworktest.py 

Printing each pncnetwork record
 Beltway, 2020-04-26 23:18:13
Keystone, 2020-04-26 23:49:13
Freedom, 2020-04-26 23:00:19
New England, 2020-04-26 23:50:24

NAME PNCChecker-2020-04-27 14:56:00.txt
PATH /opt/scripts/output/PNCChecker-2020-04-27 14:56:00.txt
ERROR  (421, b'4.3.2 Service not available')

(Apr-27-2020, 11:01 PM)tpolim008 Wrote:
(Apr-27-2020, 10:56 PM)Larz60+ Wrote: Please post the complete, unaltered error traceback.
It contains valuable information, showing what leads up to the actual error.

Hello please Here is the error from the script being ran. I did verify that my server is whitelisted and I was able to send a test mail from the server to myself.

tpolim001@srv01 ~]$ ./pncnetworktest.py 

Printing each pncnetwork record
 Beltway, 2020-04-26 23:18:13
Keystone, 2020-04-26 23:49:13
Freedom, 2020-04-26 23:00:19
New England, 2020-04-26 23:50:24

NAME PNCChecker-2020-04-27 14:56:00.txt
PATH /opt/scripts/output/PNCChecker-2020-04-27 14:56:00.txt
ERROR  (421, b'4.3.2 Service not available')

here is a test mail result using sendmail from my server

[tpolim001@engsrv01 ~]$ echo "Subject: sendmail test" | sendmail -v [email protected]
[email protected]... Connecting to [127.0.0.1] via relay...
220 engsrv01 ESMTP Sendmail 8.15.2/8.15.2; Mon, 27 Apr 2020 19:03:10 -0400
>>> EHLO engsrv01
250-srv01 Hello localhost [127.0.0.1], pleased to meet you
250-ENHANCEDSTATUSCODES
250-PIPELINING
250-8BITMIME
250-SIZE
250-DSN
250-ETRN
250-AUTH GSSAPI
250-STARTTLS
250-DELIVERBY
250 HELP
>>> STARTTLS
220 2.0.0 Ready to start TLS
>>> EHLO srv01
250-eng01 Hello localhost [127.0.0.1], pleased to meet you
250-ENHANCEDSTATUSCODES
250-PIPELINING
250-8BITMIME
250-SIZE
250-DSN
250-ETRN
250-AUTH GSSAPI
250-DELIVERBY
250 HELP
>>> MAIL From:<tpolim001@srv01> SIZE=23 AUTH=tpolim001@engsrv01
250 2.1.0 <tpolim001@engsrv01>... Sender ok
>>> RCPT To:<[email protected]>
>>> DATA
250 2.1.5 <[email protected]>... Recipient ok
354 Enter mail, end with "." on a line by itself
>>> .
250 2.0.0 03RN3ANj008236 Message accepted for delivery
[email protected]... Sent (03RN3ANj008236 Message accepted for delivery)
Closing connection to [127.0.0.1]
>>> QUIT
221 2.0.0 engsrv01 closing connection
[tpolim001@engsrv01 ~]$
Reply
#4
it looks as though your connection is not working.
there are probably other exceptions that aren't being shown.

change your exception routine to:
except Exception as e:
    print("ERROR ", str(e))
    logger.error('message')
    raise
Reply
#5
(Apr-27-2020, 11:08 PM)Larz60+ Wrote: it looks as though your connection is not working.
there are probably other exceptions that aren't being shown.

change your exception routine to:
except Exception as e:
    print("ERROR ", str(e))
    logger.error('message')
    raise


AH thank you many more errors.... I can say I do have a route to my mail relay server as well and dscp markings are correct from the network side as well.

[tpolim001@srv01 ~]$ ./pncnetworktest.py 

Printing each pncnetwork record
 Beltway, 2020-04-26 23:18:13
Keystone, 2020-04-26 23:49:13
Freedom, 2020-04-26 23:00:19
New England, 2020-04-26 23:50:24

NAME PNCChecker-2020-04-27 19:10:00.txt
PATH /opt/scripts/output/PNCChecker-2020-04-27 19:10:00.txt
ERROR  [Errno 113] No route to host
Traceback (most recent call last):
  File "./pncnetworktest.py", line 68, in <module>
    s = smtplib.SMTP('mailrelay.xxxxxxxx.net')
  File "/usr/lib64/python3.6/smtplib.py", line 251, in __init__
    (code, msg) = self.connect(host, port)
  File "/usr/lib64/python3.6/smtplib.py", line 336, in connect
    self.sock = self._get_socket(host, port, self.timeout)
  File "/usr/lib64/python3.6/smtplib.py", line 307, in _get_socket
    self.source_address)
  File "/usr/lib64/python3.6/socket.py", line 724, in create_connection
    raise err
  File "/usr/lib64/python3.6/socket.py", line 713, in create_connection
    sock.connect(sa)
OSError: [Errno 113] No route to host
[tpolim001@srv01 ~]$ 
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Sending Attachments via smtplib [SOLVED] AlphaInc 3 2,146 Oct-28-2021, 12:39 PM
Last Post: AlphaInc
  Sending random images via smtplib [SOLVED] AlphaInc 0 1,683 Oct-19-2021, 10:10 AM
Last Post: AlphaInc
  [UnicodeEncodeError from smtplib] yoohooos 0 3,380 Sep-25-2021, 04:27 AM
Last Post: yoohooos
  Understanding The Arguments for SMTPlib - sendmail JoeDainton123 3 2,716 Aug-03-2020, 08:34 AM
Last Post: buran
  TimeOutError when trying to initiate smtplib.SMTP thecosmos 0 3,328 Jun-19-2020, 05:30 AM
Last Post: thecosmos
  smtplib: string formatting not carrying over to email ClassicalSoul 1 2,643 Apr-22-2020, 09:58 PM
Last Post: bowlofred
  Issue with text encoding ans smtplib.SMTP.sendmail() JustSomeUsername383 1 4,137 Jul-23-2019, 03:15 PM
Last Post: JustSomeUsername383
  smtplib mail without subject anna 2 2,467 Apr-24-2019, 05:44 AM
Last Post: anna
  Smtplib: What does context argument means? Pythenx 1 3,076 Mar-27-2019, 06:25 PM
Last Post: nilamo
  SMTPLIB MIMEText HTML - Words being broken GaryK 2 3,764 Apr-16-2018, 04:08 PM
Last Post: GaryK

Forum Jump:

User Panel Messages

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