pyramid_mailer not sending emails? - python

New to Pyramid here, and trying to set up pyramid_mailer to send an email to myself:
I have in development.ini:
mail.host = smtp.gmail.com
mail.username = EMAIL#gmail.com
mail.password = PASSWORD
mail.port = 587
mail.ssl = True
[handlers]
keys = console
in my project/__init__.py:
config.include('pyramid_mailer')
in my project/views.py
from pyramid_mailer.mailer import Mailer
from pyramid_mailer import get_mailer
from pyramid_mailer.message import Message
#view_config(renderer="templates/site_view.pt")
def site_view(self):
...
config.registry['mailer'] = Mailer.from_settings(settings)
mailer = request.registry['mailer']
message = Message(subject="It works!",
sender="EMAIL#gmail.cm",
recipients=["EMAIL#gmail.com"],
body="Hey there!")
mailer.send(message)
Am I missing something very fundamental here?

In fact you are missing something fundamental! :-)
.send() is a lazy-send which adds the message to the transaction manager. If you are not using pyramid_tm then the mail will not be sent at the end of the request. The transactional emailing is nice because if an exception is raised in your code after calling send(), the mail will not be sent.
Anyway, the way to make your code send is via .send_immediately().

You might want to check that and use:
mail.tls = True
Can't send emails with pyramid_mailer and gmail
also you can use .send_immediately(message, fail_silently=False)
You'd have something like that:
mail.host = smtp.gmail.com
mail.username = EMAIL#gmail.com
mail.password = PASSWORD
mail.port = 587
mail.tls = True
In your setup:
config.include('pyramid_mailer')
And then
mailer = get_mailer(request)
message = Message(subject="It works!",
sender="EMAIL#gmail.cm",
recipients=["EMAIL#gmail.com"],
body="Hey there!")
mailer.send_immediately(message, fail_silently=False)
If nothing still work, you can enable debugging using
mail.debug = True
It should dump in stdout the smtp session. If something didn't work. You'll know exactly why. If everything is fine.

Related

Receive and Print a Twilio SMS with Python

For clarification, I don't want to reply to the SMS. Every tutorial or document I've looked at is about setting up a port to listen on.
What I'm trying to do is just get the SMS and print it. I can send them fine and without problems.
Here is my sending function, and it works.
def send():
message = client.messages \
.create(
body=sendMSG,
from_='MY_TWILIO_NUMBER',
to='MY_PERSONAL_NUMBER'
)
print(message.sid)
How would you receive an SMS without Flask? Is there a way to do something similar to this method below just for receiving?
def receive():
message = client.messages \
.recieve(
from_='MY_PERSONAL_NUMBER',
to='MY_TWILIO_NUMBER'
)
print(message.sid)
I have not personally tried to get SMS messages from the logs before, always getting it directly through a webhook, but from what I see, it appears the command you might be looking for is list(). You can add filters, as shown in the API docs, and there are three filtering options. You can filter by DateSent, To, or From.
I have not tried this, but it would seem that the way to use this would be the following (adjusted from the code they supply):
# Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)
messages = client.messages.list(from='MY_PERSONAL_NUMBER', to='MY_TWILIO_NUMBER')
for record in messages:
print(record.sid)
If that doesn't work, the variables they use are actually capitalized "To" and "From", so you might try that.
After looking at that a bit, you might be looking more for this:
received = client.messages.list(to='MY_TWILIO_NUMBER')
sent = client.messages.list(from='MY_PERSONAL_NUMBER')
That will separate out those sent to you, and those sent from you

django_cron not sending email

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

Can I get the incoming message by using Mailgun?

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

Automating Gmail login in Python

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.

Error 252 : b"2.1.5 Send some mail, I'll try my best f18sm1267047wiv.14"

Hi I've written a Python script to send a simple message. The script works with my university email address. However, with gmail there seems to be a problem. I've tried using both my email and just login as a login name - same result. The error I get is:
Error 252 : b"2.1.5 Send some mail, I'll try my best f18sm1267047wiv.14"
I'm not sure what I'm doing wrong. I really couldn't find much info. All I get is the above line, nothing else. I'm running the script on a Linux machine and it was written on a linux machine.
#! /usr/bin/python3.1
def sendmail(recepient, msg):
import smtplib
# Parameters
sender = 'login#gmail.com'
password = 'password'
smtpStr = 'smtp.gmail.com'
smtpPort = 587
# /Parameters
smtp_serv = smtplib.SMTP(smtpStr, smtpPort)
smtp_serv.ehlo_or_helo_if_needed()
smtp_serv.starttls()
smtp_serv.ehlo()
recepientExists = smtp_serv.verify(recepient)
if recepientExists[0] == 250:
smtp_serv.login(sender, password)
try:
smtp_serv.sendmail(sender, recepient, msg)
except smtplib.SMTPException:
print(recepientExists[1])
else:
print('Error', recepientExists[0], ':', recepientExists[1])
smtp_serv.quit()
sendmail('receiver#gmail.com', 'hi')
It's pretty straightforward. Nobody supports VRFY because it's such an aid to spam. Pull out that check and it should work OK.

Categories