Issue in Sending mail in Bulk quantity in Python - python

I am trying to create a bulk email sender. I want the script to open form.csv that contains multiple email addresses, and send the email to them.
Problem is after sending 75 to 80 mails its give an error, total no of mail is (1000)
Simply, I need help to send more and sends the email to those addresses.
below is the src code its working fine.enter code here
import csv, smtplib, ssl
port = 587
smtp_server = "smtp.gmail.com"
login = "example#gmail.com" # paste your login
password = "jjshajcaez" # paste your password
message = """Subject: Happy New Year
To: {recipient}
From: {sender}
Dear {name},
We wish you and your family a very Happy New Year!
With warm regards, """
sender = "example#gmail.com"
context = ssl.create_default_context()
with smtplib.SMTP(smtp_server, port) as server:
server.connect('smtp.gmail.com', '587')
server.ehlo() # Can be omitted
server.starttls(context=context)
server.ehlo() # Can be omitted
server.login(login, password)
with open("form.csv") as file:
reader = csv.reader(file)
next(reader) # it skips the header row
for name, email in reader:
server.sendmail(
sender,
email,
message.format(name=name, recipient=email, sender=sender)
)
print(f'Sent to {name}')
form.csv
#name, email
Test, test#gmail.com
is there any suggestion how to modify the code... so that it can send mail at once and store the log file on the system.

Related

How can I add a Subject to my email to send via SMTP?

How can I add a subject in it like I did in a normal message? When I am trying to send an email with the code below, it is showing with no Subject:
import smtplib, ssl
email = "fromemailhere"
password = "passwordhere"
receiver = "toemailhere"
message = """
Hello World
"""
port = 465
sslcontext = ssl.create_default_context()
connection = smtplib.SMTP_SSL(
"smtp.gmail.com",
port,
context=sslcontext
)
connection.login(email, password)
connection.sendmail(email, receiver, message)
print("sent")
I have seen this example, but I don't understand how can I do this in my project. Can anyone tell me with a code example?
I am not a Python developer, but I want to use this program.
It is fairly straight forward. Use email library (documentation). AFAIK it is a standard built in library, so no additional installation required. Your could would look like this:
import smtplib, ssl
from email.mime.text import MIMEText
email = "fromemailhere"
password = "passwordhere"
receiver = "toemailhere"
message = """
Hello World
"""
message = MIMEText(message, "plain")
message["Subject"] = "Hello World"
message["From"] = email
port = 465
sslcontext = ssl.create_default_context()
connection = smtplib.SMTP_SSL(
"smtp.gmail.com",
port,
context=sslcontext
)
connection.login(email, password)
connection.sendmail(email, receiver, message.as_string())
print("sent")

How to resume sending emails with smtplib and multipe smtps?

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!

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..")

Python: How to pass email text body to Office365 Email

Trying to make the script below work for office365. Sends out an email but I cannot get the script to recognize the actual email text body (only the Subject line being sent). Below script worked for gmail. Any ideas where I need to modify?
Thanks!
import smtplib, ssl
port = 587
smtp_server = "smtp.office365.com"
sender_email = "me#email.com"
receiver_email = {'User1': 'user1#email.com'}
password = "password"
subject = input('Enter the subject line: ')
message = input('Enter the message: ')
email = """\
Subject: %s
%s
""" % (subject, message)
for key, value in receiver_email.items():
context = ssl.create_default_context()
with smtplib.SMTP(smtp_server, port) as server:
server.ehlo() # Can be omitted
server.starttls(context=context)
server.ehlo() # Can be omitted
server.login(sender_email, password)
server.sendmail(sender_email, value, email)
server.quit()
was missing a "\n" in the email object. It now works.
email = """\
Subject: %s\n
%s
""" % (subject, message)

Blocked by Spamhaus When Trying to Validate Email Using Python

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.

Categories

Resources