James Methew
James Methew

Reputation: 21

Send Mail with python using gmail smtp

I am using following code

import smtplib
import mimetypes
from email.mime.multipart import MIMEMultipart
from email import encoders
from email.message import Message
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.text import MIMEText

emailfrom = "[email protected]"
emailto = "[email protected]"
fileToSend = "hi.csv"
username = "user"
password = "password"

msg = MIMEMultipart()
msg["From"] = emailfrom
msg["To"] = emailto
msg["Subject"] = "help I cannot send an attachment to save my life"
msg.preamble = "help I cannot send an attachment to save my life"

ctype, encoding = mimetypes.guess_type(fileToSend)
if ctype is None or encoding is not None:
    ctype = "application/octet-stream"

maintype, subtype = ctype.split("/", 1)

if maintype == "text":
    fp = open(fileToSend)
    # Note: we should handle calculating the charset
    attachment = MIMEText(fp.read(), _subtype=subtype)
    fp.close()
elif maintype == "image":
    fp = open(fileToSend, "rb")
    attachment = MIMEImage(fp.read(), _subtype=subtype)
    fp.close()
elif maintype == "audio":
    fp = open(fileToSend, "rb")
    attachment = MIMEAudio(fp.read(), _subtype=subtype)
    fp.close()
else:
    fp = open(fileToSend, "rb")
    attachment = MIMEBase(maintype, subtype)
    attachment.set_payload(fp.read())
    fp.close()
    encoders.encode_base64(attachment)
attachment.add_header("Content-Disposition", "attachment", filename=fileToSend)
msg.attach(attachment)

server = smtplib.SMTP("smtp.gmail.com:587")
server.starttls()
server.login(username,password)
server.sendmail(emailfrom, emailto, msg.as_string())
server.quit()

I am getting error "Username and password not accepted. learn more at\n5.7.8 https://support.google.com/mail/answer/14257" as per written over there, i have changed Allow less secure apps: ON

but getting same error! any help??

Upvotes: 2

Views: 1733

Answers (1)

PascalVKooten
PascalVKooten

Reputation: 21461

The whole purpose of yagmail (I'm the developer) is to make it really easy to send emails, especially with HTML or attachment needs.

Try the following code:

import yagmail
yag = yagmail.SMTP(username, password)
yag.send(emailto, subject = "I now can send an attachment", contents = fileToSend)

Notice the magic here: contents equal to a file path will automatically attach, using correct mimetype.

If you want to send text with it you can do like so:

contents = ['Please see the attachment below:', fileToSend, 'cool huh?']

If you want to talk about the attachment instead of sending it, just make sure no argument in the list is ONLY the filepath.

contents = 'This filename will not be attached ' + fileToSend

You can get yagmail by using pip to install it:

pip install yagmail # Python 2
pip3 install yagmail # Python 3

Upvotes: 2

Related Questions