i have a task to sending mail take the time in database in celery but when it work it send all to user in all time but not one user in their time , (example : A has sent to 8:30 and b has send to 9:30) but when it work it send both to A and B in 8:30 , A and B in 9:30 , how can i fix that ?
#shared_task
def send_email_spetime():
top_article = Article.objects.all()[0]
article1 = Article.objects.all()[1:3]
article2 = Article.objects.all()[3:5]
last_article = Article.objects.all()[5:8]
context = {
'top_article': top_article,
'article1': article1,
'article2': article2,
'last_article': last_article,
}
#Sending the email to UserMail
# Sending the Email
users_mail = UserMail.objects.all()
for each_user in users_mail:
if each_user.auto_send_mail == False:
msg_plain = render_to_string('timeset/email_templates.txt')
msg_html = render_to_string('timeset/index3.html', context)
subject = "NEWS"
recepient = each_user.user_mail
send_mail(subject, msg_plain, EMAIL_HOST_USER, [recepient], html_message=msg_html, fail_silently=False)
send_email_spetime.apply_async(eta=each_user.time_set + timedelta(minutes=1))
Related
I have used this code to send messages for my chat app, but when I add notifications it doesn't work. help me please
Note: i use django-notifications-hq
def send(request):
if request.user.is_anonymous or request.user.is_active == False:
return redirect('/accounts/login')
if request.method == 'POST':
sender = request.POST.get("username")
receiver = request.POST.get("friend")
message = request.POST.get("message")
message = message.strip()
if (message == "") or (request.user.username != sender):
return redirect('/room/'+receiver)
if sender == receiver:
return redirect('/')
newmessage = Message(sender=sender, receiver=receiver, message=message)
newmessage.save()
if newmessage.save():
sender = request.POST.get("username")
receiver = request.POST.get("friend")
message = request.POST.get("message")
notify.send(sender, recipient=receiver, verb='Message',
description=message, level='light')
return HttpResponse("message sent")
return redirect('/')
I try to send an email with django , its working fine but i want to send a HttpReponse or somthing like that after the email sent , is that possible to keep using thread for that ?
class EmailThread(threading.Thread):
def __init__(self, subject, html_content, recipient_list, sender,name):
self.subject = subject
self.recipient_list = recipient_list
self.html_content = html_content
self.sender = sender
threading.Thread.__init__(self)
self.name= name
def run(self):
msg = EmailMessage(self.subject, self.html_content, self.sender, self.recipient_list)
msg.attach_file('/tmp/{username}.{filename}'.format(username=self.name,filename='proformas')+ '.pdf')
msg.content_subtype = "html" # Main content is now text/html
msg.encoding = 'utf-8'
if(msg.send()):
print('yes')
return HttpResponse('SENT')
def send_mail(request,pk):
commande = get_object_or_404(Commande,id=pk)
name = commande.Client.Raison_social
html_nadjib = render_to_string('Proformas/msg.html',{'raison_social':name,'Date':datetime.date.today()})
to_emails = ['adzadadazda#outlook.com']
subject = "azdzadaz"
sender = 'aazdazdazadazdb#gmail.com'
# EmailThread(subject, html_nadjib, to_emails, sender, name).start()
if(EmailThread(subject, html_nadjib, to_emails, sender, name).start()):
return HttpResponse('SENT')
else:
return HttpResponse('not sent')
I am trying to embed the link of the issue id from JIRA.
I want JIRA issue id to be an embedded link to the JIRA.
class ComplainceServer():
def __init__(self, jira_server, username, password, encoding='utf-8'):
if jira_server is None:
error('No server provided.')
#print(jira_server)
self.jira_server = jira_server
self.username = username
self.password = password
self.encoding = encoding
def checkComplaince(self, appid, toAddress):
query = "/rest/api/2/search?jql=issuetype = \"Application Security\" AND \"Prod Due Date\" < now()
request = self._createRequest()
response = request.get(query, contentType='application/json')
# Parse result
if response.status == 200 and action == "warn":
data = Json.loads(response.response)
print "#### Issues found"
issues = {}
msg = "WARNING: The below tickets are non-complaint in fortify, please fix them or raise exception.\n"
issue1 = data['issues'][0]['key']
for item in data['issues']:
issue = item['key']
issues[issue] = item['fields']['summary']
print u"* {0} - {1}".format(self._link(issue), item['fields']['summary'])
print "\n"
data = u" {0} - {1}".format(self._link(issue), item['fields']['summary'])
msg += '\n'+ data
SOCKET_TIMEOUT = 30000 # 30s
email = SimpleEmail()
email.setHostName('smtp.com')
email.setSmtpPort(25)
email.setSocketConnectionTimeout(SOCKET_TIMEOUT);
email.setSocketTimeout(SOCKET_TIMEOUT);
email.setFrom('R#group.com')
for toAddress in toAddress.split(','):
email.addTo(toAddress)
email.setSubject('complaince report')
email.addHeader('X-Priority', '1')
email.setMsg(str(msg))
email.send()
def _createRequest(self):
return HttpRequest(self.jira_server, self.username, self.password)
def _link(self, issue):
return '[{0}]({1}/browse/{0})'.format(issue, self.jira_server['url'])
This is the calling function. APPid and toAddress will be passed in from different UI.
from Complaince import ComplainceServer
jira = ComplainceServer(jiraServer, username, password)
issues = jira.checkComplaince(appid, toAddress)
I want issueid to be an embedded link.
currently the email sends as below:
MT-4353(https://check.com/login/browse/MT-4353) - Site Sc: DM isg_cq5
but i want [MT-4353] as hyperlink to the URL https://check.com/login/browse/MT-4353
I got an exception when i create a sms to send
here is my functions
def send_sms(to_number, body):
account_sid = settings.TWILIO_ACCOUNT_SID
auth_token = settings.TWILIO_AUTH_TOKEN
twilio_number = '+15005550006'
client = TwilioRestClient(account_sid, auth_token)
try :
client.messages.create(to=to_number,
from_=twilio_number,
body=body)
except Exception as e:
print e.message
def generate_code():
return str(random.randrange(100000, 999999))
def send_confirmation_code(request,to_number):
verification_code = generate_code()
send_sms(to_number, verification_code)
request.session['verification_code'] = verification_code
return verification_code
I have a django app and I use mandrill for mails sending.
Till recently, I was sending simple mails and it was working great.
But now, I want to send mails with attachments, so I changed my message
construction to this:
def construct_message(self):
content = self.get_content()
attachments = self.kwargs.get('attachments', None)
message = {} if not attachments else MIMEMultipart()
message['subject'] = content['subject']
message['text'] = content['txt']
message['html'] = content['html']
message['from_email'] = self.sender
message['from_name'] = '***'
recipients = self._get_recipients()
if attachments:
message['to'] = ", ".join([r["email"] for r in recipients])
else:
message['to'] = recipients
message['cc'] = []
message['bcc'] = []
if attachments:
for a in attachments:
part = MIMEApplication(open(a,"rb").read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(a))
message.attach(part)
message = message.as_string()
return message
def send_message(self, message):
"""Actually send the message."""
api_key = settings.MANDRILL_API_KEY_INTERNAL if self.is_internal else settings.MANDRILL_API_KEY_EXTERNAL
key_type_str = "internal" if self.is_internal else "external"
logging.debug("Sending mail through %s API key %s" % (key_type_str, api_key))
mandrill_client = mandrill.Mandrill(api_key)
return mandrill_client.messages.send(message=message)
And since then, I get the following response from mandrill API call:
ValidationError: Validation error: {"message":"Please enter an array"}
Do you have an idea, what am I doing wrong?
Thanks, Alex A.