text = AlertSMSText, message html = HTMLEmailBody, message The comma operation you are using here does not create a new string but a tuple. .encode() is a method of Python's str class. The tuple class doesn't have such a method hence the error. Using concatenation... text = AlertSMSText + message html = HTMLEmailBody + message ...does result in a new string, and it will also preserve new line characters \n (for what is probably going on with you later then ord('\n') -> 10). I take it if you print text or html after this section it displays it as intended yes? I'm not familiar with Email.MimeText() but it seems to be what is calling .encode() and which throws your error (would have been useful additional information rather than just the error itself). Take a look at the documentation for it, especially why you are passing in the "plain" argument. 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. How are you determining this? Note there is a difference between not having the data and not rendering it as expected. Answer from wotquery on reddit.com
🌐
Reddit
reddit.com › r/learnpython › 'tuple' object has no attribute 'encode' for stmplib, two variables into one variable?
r/learnpython on Reddit: 'tuple' object has no attribute 'encode' for stmplib, two variables into one variable?
April 29, 2022 -

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
Discussions

AttributeError: 'int' object has no attribute 'encode' when converting Tuple
Describe the issue or bug When trying to convert tuple from Python to R the error below is thrown. The code used is pulled straight from the docs. To Reproduce def tuple_str(tpl): res = StrSexpVect... More on github.com
🌐 github.com
1
July 27, 2021
python - GeoPandas - can't write to file because field names are tuples (AttributeError) - Geographic Information Systems Stack Exchange
I have created a new shapefile by dissolving and computing centroids from an existing shapefile. I have also aggregated values of the existing shapefile to use in the new shapefile. However, when I... More on gis.stackexchange.com
🌐 gis.stackexchange.com
October 24, 2022
AttributeError: 'tuple' object has no attribute 'encode'
I get an error when sending a request from a C# client library stemming from the parse_options_header. This error only started cropping up in 0.0.7 and did not exist beforehand. Here's some sam... More on github.com
🌐 github.com
8
February 7, 2024
AttributeError: 'tuple' object has no attribute 'encode' - MySQL.connector.Python - Stack Overflow
Alrighty So this is the error Traceback (most recent call last): File "C:/Users/Mandem/PycharmProjects/untitled/Pranks/Lib/site-packages/Ada.py", line 161, in mycursor. More on stackoverflow.com
🌐 stackoverflow.com
🌐
Narkive
comp.lang.python.narkive.com › hROupzov › attributeerror-tuple-object-has-no-attribute-encode
AttributeError: 'tuple' object has no attribute 'encode'
Post by erikcw It raises this error: AttributeError: 'tuple' object has no attribute 'encode' What does? I imagine that this error comes from a call to a cursor object's execute method. In other words, I imagine that you may be cursor.execute(*sql) Not that there would be anything obviously wrong with that: you are keeping the string and its parameters separate, after all.
🌐
LearnDataSci
learndatasci.com › solutions › python-attributeerror-tuple-object-has-no-attribute
Python AttributeError: 'tuple' object has no attribute – LearnDataSci
If we call the function and attempt to access the tuple's elements with dot-access, i.e. as an attribute, we will see the error: ... --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-5-2f0480fa9e27> in <module> ----> 1 val_1 = create_tuple().val_1 AttributeError: 'tuple' object has no attribute 'val_1'
🌐
GitHub
github.com › rpy2 › rpy2 › issues › 818
AttributeError: 'int' object has no attribute 'encode' when converting Tuple · Issue #818 · rpy2/rpy2
July 27, 2021 - --------------------------------------------------------------------------- TypeError Traceback (most recent call last) ~/.local/lib/python3.8/site-packages/rpy2/rinterface_lib/sexp.py in from_object(cls, obj) 598 try: --> 599 mv = memoryview(obj) 600 res = cls.from_memoryview(mv) TypeError: memoryview: a bytes-like object is required, not 'tuple' During handling of the above exception, another exception occurred: AttributeError Traceback (most recent call last) /tmp/ipykernel_12811/1038426996.py in <module> 25 from rpy2.robjects.conversion import Converter, localconverter 26 with localconvert
Author   Unexas
🌐
GitHub
github.com › Kludex › python-multipart › issues › 78
AttributeError: 'tuple' object has no attribute 'encode' · Issue #78 · Kludex/python-multipart
February 7, 2024 - Traceback (most recent call last): File ".\bug.py", line 3, in <module> parse_options_header( File "M:\Metrized\in-progress\metrized-cv\venv\lib\site-packages\multipart\multipart.py", line 118, in parse_options_header options[key.encode('latin-1')] = value.encode('latin-1') AttributeError: 'tuple' object has no attribute 'encode' With python-multipart==0.0.6, the output is: b'form-data' {b'name': b'parameters', b'filename': b'path\to\x0cile.png', b'filename*': b"utf-8''C:\Users\name\path\to3\file.png"} I believe a fix in parse_options_header could be (multpart.py:111-112): for param in params: key, value = param if isinstance(value, tuple): <---- These lines value = value[-1] <---- 👍React with 👍3jbvirt, bdenglish and violetanna ·
Author   lorenpike
Find elsewhere
🌐
Reddit
reddit.com › r/django › attributeerror: 'tuple' object has no attribute 'encode'
r/django on Reddit: AttributeError: 'tuple' object has no attribute 'encode'
August 13, 2020 -

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.

🌐
CopyProgramming
copyprogramming.com › howto › attributeerror-tuple-object-has-no-attribute-encode
AttributeError: 'tuple' object has no attribute 'encode' - Complete Guide & Solutions 2026 - Attributeerror: 'tuple' object has no attribute 'encode'
December 22, 2025 - The AttributeError: 'tuple' object has no attribute 'encode' is a common Python programming error that occurs when developers attempt to call the method on a tuple object instead of a string. In Python, the method is exclusively a string operation—tuples do not have this method, making the ...
🌐
GitHub
github.com › django › channels_redis › issues › 334
AttributeError: 'tuple' object has no attribute 'decode' when configuring using tuples · Issue #334 · django/channels_redis
October 21, 2022 - File "[..]lib/python3.10/site-... errors) if x else '' for x in args) File "/usr/lib/python3.10/urllib/parse.py", line 112, in <genexpr> return tuple(x.decode(encoding, errors) if x else '' for x in args) AttributeError: 'tuple' object has no attribute 'decode'...
Author   vanschelven
🌐
GitHub
github.com › pylakey › aiotdlib › issues › 1
'tuple' object has no attribute 'encode' · Issue #1 · pylakey/aiotdlib
July 17, 2021 - Traceback (most recent call last): File "/root/mm.py", line 26, in asyncio.run(main()) File "/usr/lib/python3.9/asyncio/runners.py", line 44, in run return loop.run_until_complete(main) File "/usr/lib/python3.9/asyncio/base_events.py", line 642, in run_until_complete return future.result() File "/root/mm.py", line 13, in main client = Client( File "/usr/local/lib/python3.9/dist-packages/aiotdlib/client.py", line 253, in init md5_hash.update((self.phone_number or self.bot_token).encode('utf-8')) AttributeError: 'tuple' object has no attribute 'encode' Reactions are currently unavailable ·
Author   morteza102030
🌐
Bytes
bytes.com › home › forum › topic › python
AttributeError: 'tuple' object has no attribute 'encode' - Python
May 4, 2007 - Hi, I'm trying to build a SQL string sql = """INSERT INTO ag ('cid', 'ag', 'test') VALUES(%i, %s, %d)""", (cid, ag, self.data[parent][child]['results']['test']) It raises this error: AttributeError: 'tuple' object has no attribute 'encode' Some of the variables are unicode (test and ag) - is that what is causing this error?
🌐
Reddit
reddit.com › r/learnpython › tuple' object has no attribute 'decode'
r/learnpython on Reddit: tuple' object has no attribute 'decode'
December 12, 2020 -

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()

Top answer
1 of 3
2
Check the doc for what socket.recvfrom() returns. Which is a tuple containing the text and the replying address. If you want to decode the data received (which is inside the tuple) then you need to get it out of the tuple first. Something like: answer = clientSocket.recvfrom(2048) (data, address) = answer print(data.decode()) You'll probably need to specify the encoding, perhaps "utf-8".
2 of 3
1
hey thanks guys, i have it working now. ill paste the code. thanks for the help server ------ import socket sPort = 12000 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # creat socket object s.bind(('',sPort)) # bind with localhost(127.0.0.1) and socket print ('server is Ready') # print that the server is ready to recieve the data while 1: message, clientAddress = s.recvfrom(2048) # recieve data from client message2, clientAddress = s.recvfrom(2048) message3, clientAddress = s.recvfrom(2048) number1  = (message.decode()) # decode data from client and assign it to an var number2 = (message2.decode()) number3 = (message3.decode()) number4 = int(number3) if (number4 == 1) : # if, elif to select the operation from user depending on the input from client modMessage1 = int(number1) + int(number2) #change the string recieved into a int modMessage = str(modMessage1) # change the int answer back to a str s.sendto(modMessage.encode(), clientAddress) #encode the string and pass it back to client # each section does the same as the first depending on the client input. elif (number4 == 2 ) : modMessage1 = int(number1) - int(number2) modMessage = str(modMessage1) s.sendto(modMessage.encode(), clientAddress) elif (number4 == 3 ) : modMessage1 = int(number1) * int(number2) modMessage = str(modMessage1) s.sendto(modMessage.encode(), clientAddress) elif (number4== 4 ) : modMessage1 = int(number1) / int(number2) modMessage = str(modMessage1) s.sendto(modMessage.encode(), clientAddress) client ------ import socket serverIP = "localhost" sPort = 12000 cs = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # creat socket object message = input('numer1\r\n') # read in first number in sum message2 = input('numebr2\r\n') # read in second number in sum message3 = input('1 to add, 2 for subtract, 3 for multiply, 4 for divide \r\n') # read in waht math operation user would like to do # send data to server make sure to encode it... cs.sendto(message.encode(), (serverIP, sPort)) cs.sendto(message2.encode(), (serverIP, sPort)) cs.sendto(message3.encode(), (serverIP, sPort)) # recieve modifed data from server and print it to terminal modMessgae = cs.recv(2048) print (modMessgae.decode()) # closesocket cs.close()
🌐
The Coding Forums
thecodingforums.com › archive › archive › python
AttributeError: 'tuple' object has no attribute 'encode' | Python | Coding Forums
April 5, 2007 - Here is the full error: (sorry) Traceback (most recent call last): File "/home/erik/Desktop/wa.py", line 178, in ? curHandler.walkData() File "/home/erik/Desktop/wa.py", line 91, in walkData sql = """INSERT INTO ag ('cid', 'ag', 'test') VALUES(%i, %s, %d)""", (cid.encode("utf-8"), ag, self.data[parent][child]['results']['test']) AttributeError: 'long' object has no attribute 'encode' sql = """INSERT INTO ag ('cid', 'ag', 'test') VALUES(%i, %s, %d)""", (cid.encode("utf-8"), ag, self.data[parent][child]['results']['test']) self.cursor.execute(sql) Now, I changed all ofth e %i/%d to %s, and changed self.cursor.execute(sql) to self.cursor.execute(*sql) and it seems to be working now!