This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Receive and send emails in python
I tried searching but couldn't find a simple way to send an email.
I'm looking for something like this:
from:"Test1#test.com"#email sender
To:"test2#test.com"# my email
content:open('x.txt','r')
Everything I've found is complicated really: my project doesn't need so many lines.
Please, I like to learn: leave comments in each code and explain
The docs are pretty straitforward:
# Import smtplib for the actual sending function
import smtplib
# Import the email modules we'll need
from email.mime.text import MIMEText
# Open a plain text file for reading. For this example, assume that
# the text file contains only ASCII characters.
fp = open(textfile, 'rb')
# Create a text/plain message
msg = MIMEText(fp.read())
fp.close()
# me == the sender's email address
# you == the recipient's email address
msg['Subject'] = 'The contents of %s' % textfile
msg['From'] = me
msg['To'] = you
# Send the message via our own SMTP server, but don't include the
# envelope header.
s = smtplib.SMTP()
s.sendmail(me, [you], msg.as_string())
s.quit()
import smtplib
def prompt(prompt):
return raw_input(prompt).strip()
fromaddr = prompt("From: ")
toaddrs = prompt("To: ").split()
print "Enter message, end with ^D (Unix) or ^Z (Windows):"
# Add the From: and To: headers at the start!
msg = ("From: %s\r\nTo: %s\r\n\r\n"
% (fromaddr, ", ".join(toaddrs)))
while 1:
try:
line = raw_input()
except EOFError:
break
if not line:
break
msg = msg + line
print "Message length is " + repr(len(msg))
server = smtplib.SMTP('localhost')
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
A simple example, which works for me, using smtplib:
#!/usr/bin/env python
import smtplib # Brings in the smtp library
smtpServer='smtp.yourdomain.com' # Set the server - change for your needs
fromAddr='you#yourAddress' # Set the from address - change for your needs
toAddr='you#yourAddress' # Set the to address - change for your needs
# In the lines below the subject and message text get set up
text='''Subject: Python send mail test
Hey!
This is a test of sending email from within Python.
Yourself!
'''
server = smtplib.SMTP(smtpServer) # Instantiate server object, making connection
server.set_debuglevel(1) # Turn debugging on to get problem messages
server.sendmail(fromAddr, toAddr, text) # sends the message
server.quit() # you're done
This is code I found a while back at Link and modified.
Related
I am sending the following email:
# Import smtplib for the actual sending function
import smtplib
# Import the email modules we'll need
from email.message import EmailMessage
# Open the plain text file whose name is in textfile for reading.
with open(r'C:\Users\David\Documents\Hello.txt') as fp:
# Create a text/plain message
msg = EmailMessage()
msg.set_content(fp.read())
# me == the sender's email address
# you == the recipient's email address
msg['Subject'] = 'Enquiry'
msg['From'] = "example1#hotmail.co.uk"
msg['To'] = "example2#hotmail.co.uk"
# Send the message via our own SMTP server.
s =server = smtplib.SMTP('smtp.live.com', 587)
s.send_message(msg)
s.quit()
When I send the message I get the following error:
TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
I am not sure why this is. Does anyone have any ideas?
I've masked the original email addresses.
No localhost had been set up. This did the trick!:
# Import smtplib for the actual sending function
import smtplib
# Import the email modules we'll need
from email.message import EmailMessage
# Open the plain text file whose name is in textfile for reading.
with open(r'C:\Users\David\Documents\Hello.txt') as fp:
# Create a text/plain message
msg = EmailMessage()
msg.set_content(fp.read())
# me == the sender's email address
# you == the recipient's email address
msg['Subject'] = 'yes'
msg['From'] = "example1#hotmail.com"
msg['To'] = "example2#hotmail.com"
# Login
s =server = smtplib.SMTP('smtp.office365.com', 587)
s.starttls()
s.login('example1#hotmail.com',"password")
# Sending the message
s.send_message(msg)
s.quit()
pip install wget
just install a library and go on. I was facing the same issue and I solve it by installing it.
Hello beauful people , i hope your day is doing awesome
I have a text file with my marketing emails list seperated with lines
like this : example1#gmail.com example2#yahoo.com example#hotmail.com
and i have 4 smtp server linked to my cpanel from i send my marketing
emails !!
Well i can import smtps from file to my code and it connects to the
first smtp in the list and starts sending and when one smtp is down
or timeout it goes to the next smtp BUT starting from the top of
the mail list again ,it does not continue from where the first smtp
stopped in the mail list .
This is from my code :
Function to grab my smtps from text file :
def checker(file):
with open(file, "r") as f:
lines = f.readlines()
for line in lines:
smtp_server, smtp_port, smtp_user, smtp_pass = line.rstrip('\n').split("|")
Function to generate message for every email :
def generate_messages(recipients):
with open(letter_path, 'r', encoding='utf-8') as myfile:
data = myfile.read()
for recipient in recipients:
message = EmailMessage()
message['Subject'] = letter_subject
message['From'] = Address(letter_From, *smtp_user.split("#"))
message['To'] = recipient
message.set_content(data, 'html')
yield message
Function of sending
def smtp(smtp_server, port, user, password, messages):
with smtplib.SMTP(smtp_server, port) as server:
try:
server.ehlo()
server.starttls()
server.ehlo()
server.login(user, password)
print(crayons.green(f'Connected to smtp : {smtp_server}\n'''))
for message in messages:
server.send_message(message)
print(Fore.GREEN +'\n[+]', message['To'] + f''' SENT!{time.strftime('%X')}''')
time.sleep(10)
except smtplib.SMTPException:
print(crayons.red(f'''smtp died \nSERVER : {smtp_server}\n'''))
i have thought about it a lot and i still can't find it how to let the
next smtp continue continue from where the first one stopped !!
thanks for your help in advance
The answer is easy apparently !!!
we just have to add
recipients.remove(recipient)
under the message['To'] = recipient
now we delete the recepient from the existance when the message is sent!
I'm trying to check whether an email exists or not using Python's smtplib
This is what I did:
s = smtplib.SMTP()
s.connect(mxRecord)
s.mail('my#email.com') //Here the error shows up
The error is:
Client host [...] blocked using Spamhaus. To request removal from this list see http://www.spamhaus.org/lookup.lasso (S3130)
I tried something and it worked well.
import dns.resolver, smtplib
MyEmail = "X#hotmail.com"
MyPassword = "XXX"
EmailToValidate = "X#Y.com"
record = dns.resolver.query(str.split(EmailToValidate, "#")[1], "MX")
mx = str(record[0].exchange)
server = smtplib.SMTP("smtp.live.com", 587)
server.ehlo()
server.starttls()
server.ehlo()
server.login(MyEmail, MyPassword)
server.helo("live.com")
server.connect(mx)
server.mail(MyEmail)
code, msg = server.rcpt(EmailToValidate)
print("Code: ", str(code), " message: ", msg)
the (code, message) pair will be (250, OK) if the email exists, and (550, Address Rejected) if the email does not exists.
I wrote this on hurry, so there might be some unnecessary steps.
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")
I have a Python script that loops through a list of 8 different machines and does a copy, execute, and test. I would like to receive an email after each loop. **I'm not sure what to google for this. I would appreciate any ideas that will help me with my task.
I am aware of the smtplib module, just not how to perform a certain task with it.
I did indeed check the handy search engine and found no previous questions that provided answers
Question: how would one break in the middle of a loop, send an email, then continue with the loop??????
I have an email when the script starts and an email when the script ends. I just want to be notified as the script progresses or if it fails.
Thank you in advance.
You're looking for Python's smtp library.
The example from the documentation is this:
import smtplib
def prompt(prompt):
return raw_input(prompt).strip()
fromaddr = prompt("From: ")
toaddrs = prompt("To: ").split()
print "Enter message, end with ^D (Unix) or ^Z (Windows):"
# Add the From: and To: headers at the start!
msg = ("From: %s\r\nTo: %s\r\n\r\n"
% (fromaddr, ", ".join(toaddrs)))
while 1:
try:
line = raw_input()
except EOFError:
break
if not line:
break
msg = msg + line
print "Message length is " + repr(len(msg))
server = smtplib.SMTP('localhost')
server.set_debuglevel(1)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
Use the built-in email package to create your message if there's anything nonstandard you need to do with MIMEtypes/etc. Use the built-in smtplib package to send it (and create it if you don't have to do anything fancy).