简体   繁体   中英

Unable to sent mail using Python

I have tried to go through the codes that are give on different website but every where the format is same. I am unable to send mail due to Attriute error: 'str' object has no attribute 'as_string' . that is in the line text = msg.as_string()

# -*- coding: utf-8 -*-
import pandas as pd
import io
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
import numpy as np

msg=MIMEMultipart()

require_cols = [8]
excel_file = pd.ExcelFile('test_jan20.xlsx')

print(excel_file ) 
print(excel_file.sheet_names)

df = excel_file.parse('Sheet1', index_col=8) 
print(df)


email = 'arora.prachi1999@gmail.com'
password = 'zxozxxrlifvsmrnl'
send_to_emails = ['prachi.arora@incedoinc.com', 'aditi.dhooria@incedoinc.com']
subject = 'This is a test mail'

msg= "Morning!"
msgHTML ="""
<html>
  <head></head>
  <body>
  This is a test mail using python<br>
  Regards<br><br>
  Prachi
  </body>
</html>
"""
print('checked')

# Connect and login to the email server
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(email, password)
text = msg.as_string()
print(text)

# Loop over each email to send to
for send_to_email in send_to_emails:
    # Setup MIMEMultipart for each email address (if we don't do this, the emails will concatenate on each email sent)
    msg = MIMEMultipart()
    msg['From'] = email
    msg['To'] = send_to_email
    msg['Subject'] = subject

# Attach the message to the MIMEMultipart object
msg.attach(MIMEText(message, 'plain'))
msg.attach(MIMEText(messageHTML, 'html'))

# Send the email to this specific email address
server.sendmail(email, send_to_email, message.as_string()) 
print('mail sent')

enter image description here

I think the problem is you are redefining the msg variable with "Morning." after defining msg = MIMEMultipart() which is causing you the problem.

Change msg = "Morning!" to something like message = "Morning!" Hope it works

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM