I want to create an automatic script in python that will inform me with an email when a new order is placed on my website.
So far, I found I can use cronjobs from the apache server every minute, but it seems to be overkill since I don't get orders every minute.
So I'm looking for a better solution.
Here’s the code you can call this code whenever the order is placed by the user you don’t need to automate
If you are using django you can use this:
from django.core.mail import send_mail
send_mail(
'Subject here',
'Here is the message.',
'from#example.com',
['to#example.com'],
fail_silently=False,
)
Without django you can use this :
import smtplib
sender = 'from#example.com'
receivers = ['to#example.com']
message = “This is a test e-mail message."
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receivers, message)
print "Successfully sent email"
except SMTPException:
print "Error: unable to send email"
Related
I have just installed django_cron not django_crontab though, somehow I am trying to send an email as notification but it just wouldn't work.
this is just for testing purpose so I set it to 1 minute.
the code was a bit more complex before but it didn't work so I used the most simplified way to send email in order to make sure that it's not working. Also even used it as a post method to test, and it tested out working perfectly if a post method called the follow codes
class MyCronJob(CronJobBase):
RUN_EVERY_MINS = 1 # every minute
schedule = Schedule(run_every_mins=RUN_EVERY_MINS)
code = 'Email_Test' # a unique code
def do(self):
print('######################################')
send_mail(
'Subject here from cron',
'Here is the message.',
'from#email.com',
['to#emailcom'],
fail_silently=False,
)
I tried running python manage.py runcrons and python manage.py runcrons --force and waited, (no errors, I also added the print because I want to see if the code even runs and good, I see the ################# got printed)
can someone please give me an advise?
Thanks in advance
Try a custom function for sending mail. I tried send_mail function and it did not work for me and i did not find any bug or explanation on this topic. Below is an example of sending html emails using smtplib.
import smtplib
def send_email(email, subject, message):
text = subject
html = message
msg = MIMEMultipart('alternative')
html_part = MIMEText(html, 'html')
text_part = MIMEText(text, 'plain')
msg.attach(text_part)
msg.attach(html_part)
msg['Subject'] = subject
msg['From'] = SENDER_EMAIL
msg['To'] = email
s = smtplib.SMTP(settings.GMAIL_SMTP)
s.ehlo()
s.starttls()
s.login(SENDER_EMAIL, SENDER_PASSWORD)
s.sendmail(SENDER_EMAIL, email, msg.as_string())
s.quit()
please make sure first you must have to import library from django.core.mail, to using send_mail. I know it's too late to help, but u can try this..
from django_cron import CronJobBase, Schedule
from django.core.mail import send_mail
class my_scheduled_job(CronJobBase):
RUN_EVERY_MINS = 1
schedule = Schedule(run_every_mins=RUN_EVERY_MINS)
code = 'user_dashboard.autoemail.my_scheduled_job'
def do(self):
subject= 'Send Email With Automatic Schedule'
message= 'Test send email :'
email_to= ['xxxxxxxx#gmail.com']
email_user(subject_test, message_test, email_to_test)
print ("done")
def email_user(subject, message, email_to):
email_from = 'noreply#xxxx.id'
send = send_mail(subject, message, email_from, email_to)
return send
I am trying to send a simple mail with python
import smtplib
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.login("mymail#gmail.com", "mypassword")
msg = "Hello world"
server.sendmail("mymail#gmail.com", "mymail#gmail.com", msg)
server.quit()
But I get this err:
server.login("user#gmail.com", "psw")
File "C:\Python\lib\smtplib.py", line 652, in login
raise SMTPAuthenticationError(code, resp)
smtplib.SMTPAuthenticationError: (534, b'5.7.14 <https://accounts.google.com/ContinueSignIn?sarp=1&scc=1&plt=AKgnsbuxb\n5.7.14 4i2u8qU8V3jgf6uGv8da1RAGPJyctRvIFy_kjai6aKVx_B6qVhoz_dzFpvfPC18H-jeM6K\n5.7.14 cnm2HVuq-wr-uw59hD31ms-cxMmnZuq6Z3_liDaDmu8_UqaiUwR4FUiuX2i5pPdQjJzFvv\n5.7.14 4VrEF5XT4ol2iN17gnB_jITpwzsjH9Ox3NCNcfl7SriHr5m7esc15PWI0CG_2CTlyh7RxW\n5.7.14 XhoJPajs8GMd-khOQWUqucywfrfo> Please log in via your web browser and\n5.7.14 then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/bin/answer.py?answer=78754 ef10sm13614207wjd.49 - gsmtp')
What should I do?
Thanks
It seems as if you require something that Google calls an app password.
Basically, you generate a 16 digit password, which is unique to your app. You enter this specific password in the python program, instead of the password you regularly use to log into your Google account.
This allows you to still enjoy the benefits of 2-step verification while also being able to use third party applications, such as your own python program.
Here are the instructions from Google on how to generate such an app password:
https://support.google.com/accounts/answer/185833?hl=en
you can use this code:
import smtplib
session = smtplib.SMTP('smtp.gmail.com', 587)
session.ehlo()
session.starttls()
session.login('youremail#gmail.com',' password')
headers = "\r\n".join(["from: " + 'youremail#gmail.com',
"subject: " + "test",
"to: " + 'contactemail#gmail.com',
"mime-version: 1.0",
"content-type: text/html"])
# body_of_email can be plaintext or html!
content = headers + "\r\n\r\n" + "body_of_email"
session.sendmail('youremail#gmail.com', 'contactemail#gmail.com', content)
just remember if your email is gmail after first run you get an error. after that you should login to your email account and approve access to your account from another app ( you will receive a messege after login)
You could use a free mail API such as mailgun:
import requests
def send_simple_message(target):
return requests.post(
"https://api.mailgun.net/v3/samples.mailgun.org/messages",
auth=("api", "key-3ax6xnjp29jd6fds4gc373sgvjxteol0"),
data={"from": "Excited User <excited#samples.mailgun.org>",
"to": [target],
"subject": "Hello",
"text": "Testing some Mailgun awesomeness!"})
send_simple_message('target#email.com')
Using an API like this avoids the issue of individual account authentication all together.
See also: This question for info on using smtplib
Yea, like the answer posted, it was a matter of authentication :)
I'd like to further help you with sending emails by advising the yagmail package (I'm the maintainer, sorry for the advertising, but I feel it can really help!). Note that I'm also maintaining a list of common errors there, such as the authentication error.
The whole code for you would be:
import yagmail
yag = yagmail.SMTP('user', 'pw')
yag.send(contents = msg)
Note that I provide defaults for all arguments, for example if you want to send to yourself, you can omit "to = myemail#gmail.com", if you don't want a subject, you can omit it also.
Furthermore, the goal is also to make it really easy to attach html code or images (and other files).
Where you put contents you can do something like:
contents = ['Body text, and here is an embedded image:', 'http://somedomain/image.png',
'You can also find an audio file attached.', '/local/path/song.mp3']
Wow, how easy it is to send attachments! This would take like 20 lines without yagmail ;)
Also, if you set it up once, you'll never have to enter the password again (and have it safely stored). In your case you can do something like:
import yagmail
yagmail.SMTP().send(contents = contents)
which is much more concise!
I'd invite you to have a look at the github or install it directly with pip install yagmail.
I'm having some trouble sending a message to multiple addresses using the Gmail API. I've successfully sent a message to only one address, but get the following error when I include multiple comma-separated addresses in the 'To' field:
An error occurred: <HttpError 400 when requesting
https://www.googleapis.com/gmail/v1/users/me/messages/send?alt=json
returned "Invalid to header">
I'm using the CreateMessage and SendMessage methods from this Gmail API guide:
https://developers.google.com/gmail/api/guides/sending
That guide states that the Gmail API requires messages that are RFC-2822 compliant. I again didn't have much luck using some of these addressing examples in the RFC-2822 guide:
https://www.rfc-editor.org/rfc/rfc2822#appendix-A
I'm under the impression that 'mary#x.test, jdoe#example.org, one#y.test' should be a valid string to pass into the 'to' parameter of CreateMessage, but the error that I received from SendMessage leads me to believe otherwise.
Please let me know if you can recreate this problem, or if you have any advice on where I may be making a mistake. Thank you!
Edit: Here is the actual code that yields an error...
def CreateMessage(sender, to, subject, message_text):
message = MIMEText(message_text)
message['to'] = to
message['from'] = sender
message['subject'] = subject
return {'raw': base64.urlsafe_b64encode(message.as_string())}
def SendMessage(service, user_id, message):
try:
message = (service.users().messages().send(userId=user_id, body=message)
.execute())
print 'Message Id: %s' % message['id']
return message
except errors.HttpError, error:
print 'An error occurred: %s' % error
def ComposeEmail():
# build gmail_service object using oauth credentials...
to_addr = 'Mary Smith <mary#x.test>, jdoe#example.org, Who? <60one#y.test>'
from_addr = 'me#address.com'
message = CreateMessage(from_addr,to_addr,'subject text','message body')
message = SendMessage(gmail_service,'me',message)
Getting "Invalid to header" when sending with multiple recipients (comma delimited) in a single header was a regression that was fixed on 2014-08-25.
As James says in its comment, you shouldn't waste time trying to use Gmail API when Python has excellent documented support for using SMTP : email module can compose message including attachements, and smtplib sends them. IMHO you could use Gmail API for what works out of the box but should use the robust modules form Python Standard Library when things go wrong.
It looks like you want to send a text only message : here is a solution adapted from the email module documentation and How to send email in Python via SMTPLIB from Mkyong.com:
# Import smtplib for the actual sending function
import smtplib
# Import the email modules we'll need
from email.mime.text import MIMEText
msg = MIMEText('message body')
msg['Subject'] = 'subject text'
msg['From'] = 'me#address.com'
msg['To'] = 'Mary Smith <mary#x.test>, jdoe#example.org, "Who?" <60one#y.test>'
# Send the message via Gmail SMTP server.
gmail_user = 'youruser#gmail.com'
gmail_pwd = 'yourpassword'smtpserver = smtplib.SMTP("smtp.gmail.com",587)
smtpserver = smtplib.SMTP('smtp.gmail.com')smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo
smtpserver.login(gmail_user, gmail_pwd)
smtpserver.send_message(msg)
smtpserver.quit()
See also User.drafts reference - error"Invalid to header"
Apparently this bug was recently introduced in Gmail API.
A use Mailgun to send b a email, after b receive the email and reply to a.If I want to track the email coming from b, How I can get the email?
Here is the code:
1.sendmail.py
from smtplib import SMTP
import requests
login_name = "postmaster#zzb.mailgun.org"
password = "********"
def send_message_via_smtp():
smtp = SMTP("smtp.mailgun.org", 587)
smtp.login(login_name, password)
smtp.sendmail("zebozhuang#163.com","348284770#qq.com", "Subject:mailgun test \n\n just for test.\n\n")
smtp.quit()
if __name__=="__main__":
send_message_via_smtp()
2.create_route.py
import requests
from werkzeug.datastructures import MultiDict
def create_route():
return requests.post(
"https://api.mailgun.net/v2/routes",
auth=("api", "key-9c4-t2q6fouilngjummvtv1rge7t00f2"),
data=MultiDict([("priority", 1),
("description", "Sample route"),
("expression", "match_recipient('.*#qq.com')"),
("action", "forward('qiyazhuang#gmail.com')"),
("action", "stop()")])
)
I create the route and I run the script sendmail.py.After someone who use email 348284770#qq.com reply to the other who use email zebozhuang#163.com, the Gmail
can not receive the message by using the Mailgun method 'forward'.
Could anyone tell me why?
Your messages are likely being delivered. Check the "Logs" tab of the Mailgun Control Panel.
Do you see any entries that look like this:
Routed: .*#qq.com -> qiyazhuang#gmail.com 'SUBJECT HERE'
The "Routed" prefix means that the message triggered a Route. If you're seeing this, and the next log entry is prefixed with "Delivered", the message is likely being delivered to Gmail without issue. Check your Gmail spam folder if you still don't see the messages in the inbox folder.
Disclaimer: I work for Mailgun Support. :)
I am writing a Python program that can login Gmail.
The purpose of this program is to check whether the username/password combination exists and is correct.
Since this program is to test the the username/password combination existence, it's no need to know any mail contents in Gmail.
The input of this program is a username and password.
The output of this program is either
successful login
or
login failure
Login failure could be:
existing username+wrong password
nonexisting username
My idea is to login Gmail first. Afterward, when login failure, the gmail webpage will show particular message on the login webpage. I can parse the webpage content and check whether it has that particular message.
However, I still have no idea how to login Gmail in Python. Please let me know which module can be used or write me a small piece of sample code.
Here's an idea:
Why don't you try to send an email from the account and see if it sends? You can do this with smtplib in the python standard module. There's code examples here. You'll have to look into the doc of the module, but it looks like an exception is thrown if the login fails, which should contain the details you're interested in.
In edit:
I dug up this bit of code that I wrote to do exactly that. You'll need to put a try/catch around the bit at the bottom to detect erroneous login credentials.
# Subject
now = dt.datetime.now().ctime()
subject = 'Change to system on %s' % now
# Body
body = 'Subject: %s,\n' % subject
body += 'On %s, a change to the system was detected. Details follow.\n\n' % now
relevantFiles = list(set([x.file for x in relevantChunks]))
for file in relevantFiles:
fileChunks = [x for x in relevantChunks if x.file == file]
for chunk in fileChunks:
body += '****** Affected file %s. ' % chunk.file
<some other stuff>
server = smtp.SMTP(args.host) # host = smtp.gmail.com:<port> look this bit up
server.starttls()
server.login(args.username, args.password)
server.sendmail(args.sender, args.recipient, body)
server.quit()
As an aside, I'm not quite sure why this question was down-voted, or even what it takes to be down-voted other than the fact that you asked the wrong question.
try this:
from email.mime.text import MIMEText
import smtplib
msg = MIMEText("Hello There!")
msg['Subject'] = 'A Test Message'
msg['From'] = 'username#gmail.com'
msg['To'] = 'username#gmail.com'
s = smtplib.SMTP('smtp.gmail.com:587')
s.starttls() ##Must start TLS session to port 587 on the gmail server
s.login('username', 'passsword') ##Must pass args gmail username & password in quotes to authenticate on gmail
s.sendmail('username#gmail.com',['username#gmail.com'],msg.as_string())
print("Message Sent")
This kind of things are like prohibited, that's why things like OAuth or OpenID are created. This kind of things permit the user to login without entering username and password. So be careful.