Search code examples
python-3.xbase64smtplib

Encoded image gives different code when it was send wtih smtplib


I've tried to encode an image with this method :

def resim_ac(self):
    dosya_ismi = QFileDialog.getOpenFileName(self, "Resim Aç", os.getenv("HOME"))

    with open(dosya_ismi[0], "rb") as file:

        image = file.read()

        encode_image = base64.encodestring(image)
    if  str(encode_image) != "":
        return str(encode_image)
    else:
        return ""

encoded_image equals to image: b'iVBORw0KGgoAAAANSUhEUgAAAgAAAAI...BlLm9yZ5vuPBoAAAAASUVORK5CYII=\n'(It is encoded image)

Whenever I try to send this code with email with this method:

    mesaj = MIMEMultipart()

    mesaj_govdesi2 = MIMEText(str(self.resim_ac), "plain")


    mesaj.attach(mesaj_govdesi2)


    mesaj["Subject"] = self.subject_text.text()  #LineEdit



    mail = smtplib.SMTP("smtp.gmail.com", 587)

    mail.ehlo()
    mail.starttls()

    mail.login(self.email, self.passw)  # e-mail adress and it's password
    mail.sendmail(self.email,self.email_to, mesaj.as_string())
    print("Mail Sended....")



    mail.close()

It gives me thisenter image description here rather than b'iVBORw0KGgoAAAANSUhEUgAAAgAAAAI...BlLm9yZ5vuPBoAAAAASUVORK5CYII=\n'

My question is why these two are different? And how can I make them same


Solution

  • okay I solved it. The problem is that I should define encode_image with self. So it is easily called in another function in the class.

    content = str(self.encryption())
            mesaj = MIMEMultipart()
    
            mesaj_govdesi = MIMEText(str(content), "plain")
            mesaj_govdesi2 = MIMEText(str(self.encode_image), "plain")
    
            mesaj.attach(mesaj_govdesi)
            mesaj.attach(mesaj_govdesi2)
    
    
            mesaj["Subject"] = self.subject_text.text()  #LineEdit
    
    
            try:
                mail = smtplib.SMTP("smtp.gmail.com", 587)
    
                mail.ehlo()
                mail.starttls()
    
                mail.login(self.email, self.passw)  # e-mail adress and it's password
                mail.sendmail(self.email,self.email_to, mesaj.as_string())