通过发送网格APis向多个用户发送电子邮件

时间:2014-12-29 06:36:03

标签: python django sendgrid

我是Django的新手并且在django中盯着我的第一个应用程序,我正在向我的用户发送关于特定事件的电子邮件。我正在使用SendGrid API发送电子邮件。我编写了以下代码来向单个用户发送电子邮件,这对我有用。但希望一次向多个用户发送电子邮件。我也有一张桌子供用户使用。我需要从列表中的数据库中获取所有用户,并立即向他们发送电子邮件。

请注意,我刚开始学习django,对django orm知之甚少。

这是通过html表单从用户获取消息主题和内容并发送给单个用户的功能。现在我已经硬编码了收件人的电子邮件。

def send_message(request):
    Message_Subject = str(request.POST.get('Subject'))
    Message_Content = str(request.POST.get('Content'))
    Message_Type = str(request.POST.get('optionsRadios'))
    Message.objects.create(MessageSubject= Message_Subject, MessageContent=Message_Content)
    sg = sendgrid.SendGridClient(settings.SENDGRID_USERNAME, settings.SENDGRID_PASSWORD)
    message = sendgrid.Mail()
    message.add_to('user@bar.com')
    message.set_subject(Message_Subject)
    message.set_html(Message_Content)
    message.set_text(Message_Content)
    message.set_from('Emailer System <foo@example.com>')
    status, msg = sg.send(message)
    if status == 200:
        messages.success(request, 'Your email was successfully sent.')
    else:
        messages.error(request, msg)
    return render_to_response('send_message.html', context_instance=RequestContext(request))

这是我的model.py文件

来自django.db导入模型

class Users(models.Model):
    UserID = models.IntegerField(verbose_name='User ID',max_length=255,primary_key=True,blank=True)
    UserName = models.CharField(verbose_name='User Name',max_length=254,null=True,blank=True)
    Email = models.EmailField(verbose_name='Email',max_length=254,null=True,blank=True)
    Phone = models.CharField(verbose_name='Phone Number',max_length=254,null=True,blank=True)

class Message(models.Model):
    MessageID = models.AutoField(verbose_name='Message ID',primary_key=True)
    MessageSubject = models.CharField(verbose_name='Subject',max_length=255,null=True,blank=True)
    MessageContent = models.TextField(verbose_name='Content',null=True,blank=True)
    MessageType = models.CharField(verbose_name='Message Type',max_length=255,default='Email',null=True,blank=True)

class Log_Messages(models.Model):
    LogID = models.AutoField(verbose_name='Log ID',primary_key=True)
    MessageID = models.ForeignKey(Message,verbose_name='Message ID',null=True, blank=True)
    UserID = models.ForeignKey(Users,verbose_name='User ID',null=True, blank=True)
    Status = models.BooleanField(default=False)
    SentDateTime = models.DateTimeField(default=datetime.now(), blank=None, null=None)

2 个答案:

答案 0 :(得分:3)

您需要做的就是将您的电子邮件发送到循环中,然后从数据库中读取。您应该使用django附带的表单api(请参阅文档中的Working with Forms),以便在处理用户输入时让您的生活更轻松。

这是一个帮助您入门的完整示例。

您的模型,其中Recipient是最终用户。我还将其链接到邮件,以便您可以记录每封邮件的每个收件人的递送状态:

class Message(models.Model):
    subject = models.CharField(max_length=200)
    content = models.TextField()
    mtype = models.CharField(max_length=1, choices=(('1','Normal Message'),
                                                    ('2','Other Message'),))
class Recipient(models.Model):
   email = models.EmailField()
   message = models.ForeignKey(Message)
   delivered = models.BooleanField(default=False)
   status = models.CharField(max_length=200, blank=True, null=True)

下一步是为Message模型创建一个表单。您可以将其放在views.py中,但约定是创建一个名为forms.py的新文件并将其放在那里。确保导入模型:

from .models import Message


class MessageForm(forms.ModelForm):
    class Meta:
        model = Message

现在,在您看来,您将使用该表单收集要发送的邮件,然后循环收件人并向每个邮件发送一条消息。使用收件人模型记录每次交付的状态。

最后,由于这是一个帖子请求,您应该重定向用户(而不是重新加载页面)。

def send_message(request):
    form = MessageForm(request.POST or None)
    if form.is_valid():
        data = form.save() # This the new message object that was
                           # saved from the data in the form.

        sg = sendgrid.SendGridClient(settings.SENDGRID_USERNAME,
                                     settings.SENDGRID_PASSWORD)

        for user in Recipient.objects.all():  # Loop through all users.
            message = sendgrid.Mail()
            message.add_to(user.email)  # Fetch the email address for each user.
            message.set_subject(data.subject)
            message.set_html(data.content)
            message.set_text(data.content)
            message.set_from('Django Mailer <foo@example.com>')
            status, msg = sg.send(message)
            if status == 200:
                user.received = True
            else:
                user.received = False
            user.message = data # Log which message was sent to this user
            user.status = msg # Log any error message from Sendgrid
            user.save()
         return redirect('/thank-you/')  # Redirect to some thank you page.

    return render(request, 'form.html', {'form': form})

答案 1 :(得分:0)

您可以尝试为每封电子邮件致电add_to

... 

message = sendgrid.Mail()
user_emails = Users.objects.filter(is_active=True).values_list('email', flat=True)

for email in user_emails:
    message.add_to(email)

message.set_subject(Message_Subject)
...