Python smtp send email from gmail , - python

I use python to send email from gmail.I turn gmail IMAP on also get a security password(a 16 bit password).But reply me UserName and Password not accepted.I u se the google account password,port 25,587,465(use ssl).can not work.
#! /usr/bin/python
# -*- coding: UTF-8 -*-
from email.mime.text import MIMEText
from email.header import Header
from email import encoders
import smtplib
sender = "Mygmail#gmail.com"
rec= "reciver#qq.com"
passwd = "security password"
#passwd = 'the really google account password'
message = MIMEText("邮件发送","plain","utf-8")
message['From'] =sender
message['To'] = rec
message['Subject'] =Header("from google","utf-8").encode()
smtpObj = smtplib.SMTP("smtp.gmail.com",587)
smtpObj.ehlo()
smtpObj.starttls()
smtpObj.set_debuglevel(1)
smtpObj.login(sender,passwd)
smtpObj.sendmail(sender,[rec],message.as_string)
smtpObj.close()

Try the following, it has worked for me in the past
#!/usr/bin/python
#from smtplib import SMTP # Standard connection
from smtplib import SMTP_SSL as SMTP #SSL connection
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
sender = 'example#gmail.com'
receivers = ['example#gmail.com']
msg = MIMEMultipart()
msg['From'] = 'example#gmail.com'
msg['To'] = 'example#gmail.com'
msg['Subject'] = 'simple email via python test 1'
message = 'This is the body of the email line 1\nLine 2\nEnd'
msg.attach(MIMEText(message))
ServerConnect = False
try:
smtp_server = SMTP('smtp.gmail.com','465')
smtp_server.login('#name##gmail.com', '#password#')
ServerConnect = True
except SMTPHeloError as e:
print "Server did not reply"
except SMTPAuthenticationError as e:
print "Incorrect username/password combination"
except SMTPException as e:
print "Authentication failed"
if ServerConnect == True:
try:
smtp_server.sendmail(sender, receivers, msg.as_string())
print "Successfully sent email"
except SMTPException as e:
print "Error: unable to send email", e
finally:
smtp_server.close()

Related

Is it possible to sign outgoing mail in Python?

I'm using smtplib library to send emails from python script.
import smtplib
import ssl
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def sendmail(input, topic, receiver_email):
# definitions for setup
sender_email = "EMAIL"
port = 465 # For SSL
smtp_server = "SERVER"
login = "APIKEY" # Enter your login
password = 'PASSWORD'
# set message parameters
message = MIMEMultipart("alternative")
message["Subject"] = topic
message["From"] = sender_email
message["To"] = receiver_email
part1 = MIMEText(input, "plain")
message.attach(part1)
# part2 = MIMEText(html, "html")
# message.attach(part2)
# Create secure connection with server and send email
context = ssl.create_default_context()
with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
server.login(login, password)
server.sendmail(sender_email, receiver_email, message.as_string())
I've created email certificate. It is stored in .pfx file. Is there any library or way to sign emails with this certificate?

sending email using smtplib and SSL but receiver is no receiving it

I am trying to send email from one email to another using smtplib and ssl. It's showing delivered, but there is no email at receiver end. I am trying two different codes:
Code 1:
import smtplib, ssl
port = 465
smtp_server = "myserver.com"
sender_email = "sender#myserver.com"
receiver_email = "receiver#gmail.com"
password = "mypassword"
message = """\
Subject: Hi there
This message is sent from Python."""
try:
context = ssl.create_default_context()
with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, message)
print("Sent..")
except:
print("Error!!")
code 2:
import smtplib
import os.path
from email.mime.text import MIMEText
msg = MIMEText("")
msg['Subject'] = "Hi there, This message is sent from Python."
s = smtplib.SMTP_SSL("myserver.com:465")
s.login("sender#myserver.com","mypassword")
s.sendmail("sender#myserver.com","receiver#gmail.com", msg.as_string())
s.quit()
print("done")
Can not find the problem. Any idea?
The sendmail method is a low level method that assumes that the message text is correctly formatted. And your messages do not contain the usual To: and From: headers.
The send_message method uses an EmailMessage and formats it correctly, so it can be easier to use. I would advise to change your code to:
port = 465
smtp_server = "myserver.com"
password = "mypassword"
msg = MIMEText("This message is sent from Python.")
msg['Subject'] = "Hi there"
msg['From'] = "sender#myserver.com"
msg['To'] = "receiver#gmail.com"
try:
context = ssl.create_default_context()
with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
server.login(sender_email, password)
server.send_message(msg)
print("Sent..")

Sending email using Python with smtp

I am trying to write a module as part of my code to send out email. I have this code down which does not throw any exception but it does not deliver email as I expect. Can anyone help me point out any issue this code might have? Thanks in advance!
""" before sending email with this code
I start smtp server:
python -m smtpd -n -c DebuggingServer localhost:1025
"""
#!/usr/bin/python -tt
from email.mime.text import MIMEText
from datetime import date
import smtplib
SMTP_SERVER = "localhost"
SMTP_PORT = 1025
EMAIL_TO = ["user385#dispostable.com"]
EMAIL_FROM = "user383#testdomain.com"
EMAIL_SUBJECT = "*Email Test*"
DATE_FORMAT = "%d/%m/%Y"
EMAIL_SPACE = ", "
DATA='Test email sending feature in Python'
def send_email():
msg = MIMEText(DATA)
msg['Subject'] = EMAIL_SUBJECT + " %s" %(date.today().strftime(DATE_FORMAT))
msg['To'] = EMAIL_SPACE.join(EMAIL_TO)
msg['From'] = EMAIL_FROM
mail = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
mail.sendmail(EMAIL_FROM, EMAIL_TO, msg.as_string())
mail.quit()
if __name__=='__main__':
try:
send_email()
except Exception as e:
import traceback;traceback.print_exc()
Thanks
hi can you remove the try except and run it again?
since youre using a gmail. can you try this one
import smtplib
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login("user383#gmail.com", "your-password-here")
msg = "YOUR MESSAGE!"
server.sendmail("user383#gmail.com", "user385#dispostable.com", msg)
server.quit()

How to send email from python

My Code
import smtplib
import socket
import sys
from email.mime.text import MIMEText
fp = open("CR_new.txt", 'r')
msg = MIMEText(fp.read())
fp.close()
you = "rajiv#domain.com"
me = "rajiv#domain.com"
msg['Subject'] = 'The contents of %s' % "CR_new.txt"
msg['From'] = you
msg['To'] = me
s = smtplib.SMTP('127.0.0.1')
s.sendmail(you,me, msg.as_string())
s.quit()
ConnectionRefusedError: [WinError 10061] No connection could be made
because the target machine actively refused it
Note:
Not having a SMTP server
This code will help you to send the email.
You just need to provide your email-id password.
The most important note is: don't give file name as email.py.
import socket
import sys
import smtplib
EMAIL_TO = ["rajiv#domain.com"]
EMAIL_FROM = "rajiv#domain.com"
EMAIL_SUBJECT = "Test Mail... "
msg= {}
EMAIL_SPACE = ", "
msg['Subject'] = EMAIL_SUBJECT
msg['To'] = EMAIL_SPACE.join(EMAIL_TO)
msg['From'] = EMAIL_FROM
try:
mail = smtplib.SMTP_SSL('smtp.bizmail.yahoo.com',465)
#
# if you are using gmail then use
# smtplib.SMTP_SSL('smtp.gmail.com',587)
#
mail.login("rajiv#domain.com", 'password') # you account email password..
mail.sendmail("rajiv#domain.com", EMAIL_TO, msg.as_string())
mail.quit()
except Exception,e:
print e
finally:
print "Error of email sending mail"
I would suggest using a package like yagmail, rather than trying to figure out how to get smtplib to work. Disclaimer: I'm the maintainer of yagmail.
Code would look like:
import yagmail
yag = yagmail.SMTP(host="127.0.0.1")
yag.send(to"rajiv#domain.com", subject="subject", contents="content")

Issue sending email with python?

I'm trying to make an email script in python. Here's what I have (from pythonlibrary.org):
#! /usr/bin/env python
import smtplib
import string
SUBJECT = "An email!"
TO = "me#icloud.com"
FROM = "me#gmail.com"
text = "This text is the contents of an email!"
BODY = string.join((
"From: %s" % FROM,
"To: %s" % TO,
"Subject: %s" % SUBJECT ,
"",
text
), "\r\n")
server = smtplib.SMTP('smtp.gmail.com')
server.login('me#gmail.com', 'mypassword') # Not very secure, I know, but this email is dedicated to this script
server.sendmail(FROM, [TO], BODY)
server.quit()
I get smtplib.SMTPException: SMTP AUTH extension not supported by server. Is this is so, then why does smtp.gmail.com respond at all? Is this a problem with Gmail, or my script, or something else?
Error message:
Traceback (most recent call last):
File "/Users/student/Desktop/mail.py", line 18, in <module>
server.login('*******#gmail.com', '**************')
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/smtplib.py", line 552, in login
smtplib.SMTPException: SMTP AUTH extension not supported by server.
You need to contact the gmail mail server on the submission port (587), not the default 25:
server = smtplib.SMTP('smtp.gmail.com', 587)
You also need to use server.starttls() before logging in (so that your password is not sent in the clear!). This is from a script I have and it works for me:
server = smtplib.SMTP()
server.connect("smtp.gmail.com", "submission")
server.starttls()
server.ehlo()
server.login(user, password)
Here's how to send e-mail using gmail in Python:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from email.header import Header
from email.mime.text import MIMEText
from getpass import getpass
from smtplib import SMTP_SSL
login, password = 'user#gmail.com', getpass('Gmail password:')
# create message
msg = MIMEText('message body…', _charset='utf-8')
msg['Subject'] = Header('subject…', 'utf-8')
msg['From'] = login
msg['To'] = login
# send it via gmail
s = SMTP_SSL('smtp.gmail.com', 465, timeout=10)
s.set_debuglevel(1)
try:
s.login(login, password)
s.sendmail(msg['From'], msg['To'], msg.as_string())
finally:
s.quit()
I found I had to do an ehlo() and a starttls() before sending mail via gmail:
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.ehlo()
server.login(SERVER_EMAIL,EMAIL_HOST_PASSWORD)
It shouldn't make a difference with the login, but I use a MIMEMultipart from email.mime.multipart for the body, with something like:
msg = MIMEMultipart('alternative')
msg['Subject'] = subject
msg['From'] = mFrom
msg['To'] = mTo
if textBody:
part1 = MIMEText(textBody, 'plain')
msg.attach(part1)
if htmlBody:
part2 = MIMEText(htmlBody, 'html')
msg.attach(part2)
BODY = msg.as_string()

Categories

Resources