I want sent to multiple email but i got this raise ValueError('Invalid address "%s"' % addr)
ValueError: Invalid address "['ex1#gmail.com', 'ex2#gmail.com', 'ex404#gmail.com']"
email_id = ["ex1#gmail.com","ex2#gmail.com","ex404#gmail.com"]
username = name
email = email_id
######################### mail system ####################################
htmly = get_template('email/Email.html')
d = {
's_id' : s_id,
'username': username,
'tran_id' : tran_id,
'amount' : amount
}
subject, from_email, to = 'welcome', 'your_email#gmail.com', email
html_content = htmly.render(d)
msg = EmailMultiAlternatives(subject, html_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.send()
You send array type to an another array, So array dimension was changed.
Please check like this.
email_id = ["ex1#gmail.com","ex2#gmail.com","ex404#gmail.com"]
username = name
email = email_id
######################### mail system ####################################
htmly = get_template('email/Email.html')
d = {
's_id' : s_id,
'username': username,
'tran_id' : tran_id,
'amount' : amount
}
subject, from_email, to = 'welcome', 'your_email#gmail.com', email
html_content = htmly.render(d)
msg = EmailMultiAlternatives(subject, html_content, from_email, to)
msg.attach_alternative(html_content, "text/html")
msg.send()
As other pointed out, you shouldn't enclose to in square brackets because it was already a list of strings, which is exactly what the parameter expects. See this example:
msg = EmailMultiAlternatives("subject", html_content, "from##gmail.com", ["to##gmail.com", "to2##gmail.com", "to3##gmail.com"])
Related
I am trying to send otp and then validate otp for login. I am able to send otp but it is not validating for some reason.
the code for sending otp is below and it is working fine-
class SendOTP(APIView):
permission_classes = (AllowAny, )
def post(self, request, *args, **kwargs):
email = request.data.get('email')
if email:
email = str(email)
user = User.objects.filter(email__iexact = email)
if user.exists():
key = send_otp(email)
if key:
old = User.objects.filter(email__iexact=email)
if old.exists():
old = old.first()
count = old.count
old.count = count + 1
old.save()
print('Count Increase', count)
return Response({
'status': True,
'detail': 'OTP sent successfully.'
})
code for generating 6 digit otp is -
def send_otp(email):
if email:
digits = [i for i in range(0, 10)]
key = ""
for i in range(6):
index = math.floor(random.random() * 10)
key += str(digits[index])
print(key)
return key
else:
return False
code for validating email and otp is below but it is not working-
class ValidateOTP(APIView):
permission_classes = (AllowAny, )
def post(self, request, *args, **kwargs):
email = request.data.get('email' , False)
otp_sent = request.data.get('otp', False)
if email and otp_sent:
e_mail = User.objects.filter(email__iexact = email)
if e_mail.exists():
e_mail = e_mail.first()
otp = e_mail.otp
print(otp, e_mail, otp_sent)
if str(otp_sent) == str(otp):
old.validated = True
old.save()
try:
payload = JWT_PAYLOAD_HANDLER(old)
jwt_token = JWT_ENCODE_HANDLER(payload)
update_last_login(None, old)
except User.DoesNotExist:
raise serializers.ValidationError(
'User with given email and password does not exists'
)
return Response({
'status' : True,
'email': email,
'token': jwt_token,
'detail' : 'OTP mactched.'
})
else:
return Response({
'status' : False,
'detail' : 'OTP incorrect.'
})
else:
return Response({
'status' : False,
'detail' : 'First proceed via sending otp request.'
})
else:
return Response({
'status' : False,
'detail' : 'Please provide both email and otp for validations'
})
it's is showing None for otp = e_mail.otp. is there a way to make it work?
I don't see where old.otp is being set in the SendOTP class, that's probably why it's None. Should be something like this:
old.count = count + 1
old.otp = key
old.save()
Also, if old.exists(): looks weird in ValidateOTP, since there is no references to the old variable, probably should be if e_mail.exists().
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 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))
Am trying to resend email to any one that not yet confirmed his account .
models.py
class Subscribers(Base):
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(50))
confirmed = db.Column(db.Boolean(), default=False)
def confirm(self, token):
s = Serializer(app.config['SECRET_KEY'])
try:
data = s.loads(token)
except:
return False
if data.get('confirm') != self.id:
return False
self.confirmed = True
db.session.add(self)
return True
def generate_confirmation_token(self, expiration=3600):
s = Serializer(app.config['SECRET_KEY'], expiration)
return s.dumps({'confirm': self.id})
def get_token(self, expiration=1800):
s = Serializer(app.config['SECRET_KEY'], expiration)
return s.dumps({'email': self.id}).decode('utf-8')
#staticmethod
def verify_token(token):
s = Serializer(app.config['SECRET_KEY'])
try:
data = s.loads(token)
except:
return None
id = data.get('email')
if id:
return User.query.get(id)
return None
This is the function where the confirmation process handled:
#app.route('/send-confirmation/<email>/<token>')
def confirm(token,email):
subre = Subscribers.query.filter_by(email=email).first()
if subre.confirmed:
flash('Э.почта уже подтверждена.')
return redirect(url_for('index'))
if subre.confirm(token):
subre.confirmed = True
db.session.add(subre)
db.session.commit()
send_email(subre.email, 'Благодарим Вас за подписку на наш сайт', 'auth/subscribe/thanks', subre=subre, token=token)
flash('Вы подтвердили свою электронную почту, спасибо!')
else:
flash('Ссылка для подтверждения является недействительным или истек.')
return redirect(url_for('index'))
Tell now everything is working very well, am trying to fetch each account that not yet confirmed by sending them another message asking them to confirm there account, here is the function :
#app.before_request
def resend_confirmation():
subscribers = Subscribers.query.filter_by(confirmed=False)
for sub in subscribers:
email = sub.email
token = email.generate_confirmation_token()
send_email(email, 'Подтверждение по электронной почте было отправлено Вам по электронной почте.',
'auth/email/resend', email=email, token=token)
Here am getting an error says:
AttributeError: 'unicode' object has no attribute 'generate_confirmation_token'
i tried to add __unicode__ function in the model but without avail .
Please any help .
You are trying to call generate_confirmation_token method on email, but you should use Subscribers instance:
#app.before_request
def resend_confirmation():
subscribers = Subscribers.query.filter_by(confirmed=False)
for sub in subscribers:
token = sub.generate_confirmation_token()
send_email(sub.email, 'Подтверждение по электронной почте было отправлено Вам по электронной почте.',
'auth/email/resend', email=email, token=token)
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.