Headers on a mime message must be strings. You have assigned a tuple to From, and a list to To.

Make those strings too:

message['From'] = "Michal <{}>".format(FROM)
message['To'] = ', '.join(TOADDR)
Answer from Martijn Pieters on Stack Overflow
🌐
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: 'tuple' object has no attribute 'encode' - Post.Byes
Re: AttributeError: 'tuple' object has no attribute 'encode' On Apr 5, 11:41 am, kyoso...@gmail. More on post.bytes.com
🌐 post.bytes.com
On email.send(), error 'tuple' object has no attribute 'encode'
email.send() works with: EMAIL_BACKEND = django.core.mail.backends.console.EmailBackend but not with the django_ses.SESBackend · Using python3.7.2 and Django 2.1 More on github.com
🌐 github.com
2
July 30, 2019
python - AttributeError: 'tuple' object has no attribute 'encode' (django contact form) - Stack Overflow
Communities for your favorite technologies. Explore all Collectives · Ask questions, find answers and collaborate at work with Stack Overflow for Teams More on stackoverflow.com
🌐 stackoverflow.com
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
🌐
Narkive
comp.lang.python.narkive.com › hROupzov › attributeerror-tuple-object-has-no-attribute-encode
AttributeError: 'tuple' object has no attribute 'encode'
The parameters have to be supplied as a second argument to .execute() -- your statement above is creating a tuple "sql" consisting of a string (the insert template) AND a tuple of parameters; I'm guessing you are passing just one argument to .execute(). That argument is a tuple that can't be "encoded" into a valid SQL statement.
🌐
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'
🌐
Post.Byes
post.bytes.com › home › forum › topic › python
AttributeError: 'tuple' object has no attribute 'encode' - Post.Byes
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.
🌐
GitHub
github.com › django-ses › django-ses › issues › 170
On email.send(), error 'tuple' object has no attribute 'encode' · Issue #170 · django-ses/django-ses
July 30, 2019 - email.send() works with: EMAIL_BACKEND = django.core.mail.backends.console.EmailBackend but not with the django_ses.SESBackend · Using python3.7.2 and Django 2.1
Author   wk0
🌐
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 - Always use Python 3 for new projects, ... no attribute 'encode' error is entirely preventable through careful attention to variable assignment syntax, proper type handling, and implementation of parameterized queries....
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 52137357 › attributeerror-tuple-object-has-no-attribute-encode-python
smtp - AttributeError: 'tuple' object has no attribute 'encode' python - Stack Overflow
1 AttributeError: 'tuple' object has no attribute 'decode' while trying to decode string · 4 smtplib, 'tuple' object has no attribute 'encode' 2 MIMEText - Object has no attribute 'encode' (SMTP) 0 How to fix AttributeError: 'list' object has no attribute 'encode' 3 How to fix AttributeError: "NoneType" object has no attribute "encode" using smtplib ·
🌐
The Mail Archive
mail-archive.com › python-list@python.org › msg139061.html
Re: AttributeError: 'tuple' object has no attribute 'encode'
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! -- http://mail.python.org/mailman/listinfo/python-list ... Re: AttributeError: 'tuple' object has no attribute 'enco...
🌐
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' ... 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):
Author   lorenpike
🌐
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.

🌐
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 - But it's hard to say when you didn't include that bit of code. You may need to check your database's docs to make sure it accepts unicode strings and if so, what types (utf-8, 16, 32).