I am trying to call the function send_email with the variable message in it and combining it with a string contained in AlertSMSText and assigning it to text as well as html to HTMLEmailBody.
For some reason when I do text = AlertSMSText, message and it gives me the error AttributeError: 'tuple' object has no attribute 'encode' but if I do text = AlertSMSText + message and html = HTMLEmailBody + message it works fine except it ignores \n contained in the string that AlertSMSText has in it.
SendEmailAlert.py
def send_email(message):
email_subject = JSONFileReader.SubjectEmail
sender_add = JSONFileReader.SenderEmail
receiver_add = JSONFileReader.ReceiverEmail
smsEmail_add = JSONFileReader.SMSEmailAdd # SMS email
AlertSMSText = JSONFileReader.AlertSMSText #Alert SMS Text message
HTMLEmailBody = JSONFileReader.AlertHTMLEmailBody #Alert Email message in HTML format
password = JSONFileReader.gmailPass # Password for the email you're sending from
# Below is creating the SMTP server object by giving the SMPT server an address and port number
smtp_server = smtplib.SMTP("smtp.gmail.com", 587)
smtp_server.ehlo() # setting the ESMTP protocol
smtp_server.starttls() # setting up to TLS connection
smtp_server.ehlo() # calling the ehlo() again as encryption happens on calling startttls()
smtp_server.login(sender_add, password) # logging into the senders email
rcpt = smsEmail_add.split(",") + [receiver_add] # Formats the recipients emails
# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = email_subject
msg['From'] = sender_add
msg['To'] = receiver_add
msg['Cc'] = smsEmail_add
message.encode('utf-8')
# Create the body of the message (a plain-text is for SMS and HTML is for email)
text = AlertSMSText, message
html = HTMLEmailBody, message
# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part1)
msg.attach(part2)
smtp_server.sendmail(sender_add, rcpt, msg.as_string()) #Sends the email
smtp_server.quit() #Terminates the SMTP server
ip= "10.1.50.2"
send_email(ip + " is down.\n\nPlease reply with 'Ack' to pause alerts for 60 minutes")In the JSON, the AlertSMSTextvariable equals to "Alert SMS Text": "This is an alert for your services \n\n IP: "
The output when text = AlertSMSText + message is all on one line and ignores newline \n:
This is an alert for your services IP:10.1.50.0 is down. Please reply with 'Ack' to pause alerts for 60 minutes
I want it to be:
This is an alert for your services IP:10.1.50.0 is down. Please reply with 'Ack' to pause alerts for 60 minutes
For avoid SQL-injections Django documentation fully recommend use placeholders like that:
import mysql.connector
conn = mysql.connector.connect(host='localhost',user='user1',password='puser1',db='mm')
cursor = conn.cursor()
string1 = 'test1'
insert_query = """INSERT INTO items_basic_info (item_name) VALUES (%s)"""
cursor.execute(insert_query, (string1,))
conn.commit()
You have to pass tuple/list params in execute method as second argument. And all should be fine.
Not exactly OP's problem but i got stuck for a while writing multiple variables to MySQL.
Following on from Jefferson Houp's answer, if adding in multiple strings, you must specify the argument 'multi=True' in the 'cursor.execute' function.
import mysql.connector
conn = mysql.connector.connect(host='localhost',user='user1',password='puser1',db='mm')
cursor = conn.cursor()
string1 = 'test1'
string2 = 'test2'
insert_query = """INSERT INTO items_basic_info (item_name) VALUES (%s, %s)"""
cursor.execute(insert_query, (string1, string2), multi=True)
conn.commit()
AttributeError: 'int' object has no attribute 'encode' when converting Tuple
python - GeoPandas - can't write to file because field names are tuples (AttributeError) - Geographic Information Systems Stack Exchange
AttributeError: 'tuple' object has no attribute 'encode'
AttributeError: 'tuple' object has no attribute 'encode' - MySQL.connector.Python - Stack Overflow
You are chaining heterogeneous types together, which is a certain cause of headaches.
Presumably ALC is a string, so chain first yields all the characters from the string. When it moves on to product(ALC, repeat=2), it starts yielding tuples, since that's how product works.
Just yield homogeneous types from your chain call (i.e. always yield tuples, joining them when you need a string) and the headaches disappear.
for chars in chain(*[product(ALC, repeat=n) for n in range(1,4)]):
...
a.update(''.join(chars).encode('utf-8'))
Your error is trying to convert this tuple to utf-8. Try remove this line "a.update(chars.encode('utf-8')"
When the interpreter shows "'tuple' object has no attribute 'encode' means that the object tuple does not support convert that way.
But, if you would like to convert all these things, use #coding: utf-8 in the first line of your program.
I am creating a Contact page for my django project. forms.py has name, subject, sender and message. Here's the view:
And the form:
<form method="POST">
{%csrf_token%}
{{form.as_p}}
<button type="submit">Send</button>
</form>
After I click Send I get this error: AttributeError: 'tuple' object has no attribute 'encode' and I can't seem to figure out what's wrong despite checking other questions of the same type.
I am using google SMTP server, from this link following its instructions.
You should provide the full trace back. We aren't mind readers.
Only thing I can think of is if you have other elements on the HTML form with the same name (”name”, “sender_email”, “subject”, or “message”). That, or try to remove the comma in the recipient list. I don’t think it’s the list, though.
im trying to pass number and operator to the server and pass back the answer using a UDP socket.
i get a 'tuple' object has no attribute 'decode' . on line 20 of the client. (print(answer.decode()).
if i take out the decode and input 5 + 5 it returns (b'10', ('127.0.0.1', 12456)).
can anyone help ve no idea. only been doing this for a week haha! code below
thanks alot.
client-
from socket import *
import socket
serverName = 'Localhost'
serverPort = 12456
clientSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
number1 = input ('Input number1: ')
number2 = input ('Input number2: ')
operator = input ('Select an operator: (+ / * -) ')
clientSocket.sendto(number1.encode(),(serverName,serverPort))
clientSocket.sendto(number2.encode(),(serverName,serverPort))
clientSocket.sendto(operator.encode(),(serverName,serverPort))
answer= clientSocket.recvfrom(2048)
print (answer.decode())
clientSocket.close()
server -
from socket import *
import socket
serverName = 'Localhost'
serverPort = 12456
serverSocket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
serverSocket.bind(('',12456))
print ('The server is connected')
while 1:
number1, clientAddress = serverSocket.recvfrom(2048)
number2, clientAddress = serverSocket.recvfrom(2048)
operator, clientAddress = serverSocket.recvfrom(2048)
if str(operator) == '+':
answer = int(number1.decode()) + int(number2.decode())
answer = str(answer)
serverSocket.sendto(answer.encode(),clientAddress)
elif str(operator) == '-':
answer = int(number1.decode()) - int(number2.decode())
answer = str(answer)
serverSocket.sendto(answer.encode(),clientAddress)
elif str(operator) == '/':
answer = int(number1.decode()) / int(number2.decode())
answer = str(answer)
serverSocket.sendto(answer.encode(),clientAddress)
elif str(operator) == '*':
answer = int(number1.decode()) * int(number2.decode())
answer = str(answer)
serverSocket.sendto(answer.encode(),clientAddress)
serverSocket.close()
str (don't name your variables after built-in functions, by the way) is a tuple, not a string.
str = "1",All2.encode('utf_8')
This is equivalent to the more readable:
str = ("1", All2.encode('utf_8'))
I don't know what you need the "1" for, but you might try this:
num, my_string = '1', All2.encode('utf_8')
And then decode the string:
print(my_string.decode('utf_8'))
I run into this error frequently using SageMaker Pipelines. If you are in the same boat and are lost because the logs are not at all pointing you to what portion of code is causing AttributeError: 'tuple' object has no attribute 'decode', I can tell you that for me it always occurs because I have a dangling comma that I introduced at the end of some line of code (and my IDE did not complain about).
I've realized I induce this error whenever I am copying and pasting code or am refactoring.
For example
func(
a=funcA(...),
b=funcB(...),
)
gets refactored into
a=funcA(...),
b=funcB(...),
func(
a=a,
b=b,
)
where I have just copy pasted lines of code and kept problematic commas! Instead, remember to clean them up as
a=funcA(...)
b=funcB(...)
func(
a=a,
b=b,
)