Python Sendgrid将CC添加到电子邮件

时间:2018-10-11 13:59:08

标签: python sendgrid

我正在使用SendGrid for Python。我想在电子邮件中抄送一些人。似乎他们可能不再支持电子邮件抄送,尽管我不是很肯定吗?但是肯定可以解决这个问题,但是令我惊讶的是,我在这方面找不到太多支持。

这是我的基本代码:

sg = sendgrid.SendGridAPIClient(apikey='*****')
from_email = Email(sender_address, sender_name)
to_email = Email(email_address)
subject = subject
content = Content("text/plain", email_message)
mail = Mail(from_email, subject, to_email, content)
response = sg.client.mail.send.post(request_body=mail.get())

我该如何修改它,以便在某人的电子邮件中抄送?

5 个答案:

答案 0 :(得分:2)

使用SendGrid的Personalization()Email()类对我不起作用。这就是我的工作方式:

from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail, Cc

# using a list of tuples for emails
# e.g. [('email1@example.com', 'email1@example.com'),('email2@example.com', 'email2@example.com')]
to_emails = []
for r in recipients:
  to_emails.append((r, r))

# note the Cc class
cc_emails = []
for c in cc:
  cc_emails.append(Cc(c, c))

message = Mail(
  from_email=from_email,
  to_emails=to_emails,
  subject='My Subject',
  html_content=f'<div>My HTML Email...</div>
)

if cc_emails:
  message.add_cc(cc_emails)

try:
  sg = SendGridAPIClient(os.getenv('SENDGRID_API_KEY'))            
  sg.send(message)  
except Exception as e:            
  print(f'{e}')

希望这对某人有帮助。

答案 1 :(得分:1)

我一直在查看代码:https://github.com/sendgrid/sendgrid-python/blob/master/examples/mail/mail.py

看起来您可以通过向邮件添加个性化设置来做到这一点,例如:

cc_email = Email(cc_address)
p = Personalization()
p.add_cc(cc_email)
mail.add_personalization(p)

答案 2 :(得分:0)

根据答案here,如果您向“ to_email”添加其他电子邮件,则可以抄送电子邮件。

答案 3 :(得分:0)

我解决了。圣地亚哥的答案基本上使我到了那里,但这是我需要做的:

var o = new Object();
o.method = function(x, y) {
  return x + y
};

o.method = (function(original) {
  return function(x, y) {
    var a = 'A';
    var b = 'B';
    var result = original.apply(this, [a, b]);
    return result;
  }
})(o.method);

console.log(o.method(1, 2));

如果不包括p.add_to(to_email),则它将拒绝它,因为个性化对象中没有“发送电子邮件”。另外,如果您没有在邮件对象中包含“ to_email”,它会拒绝它,因为它正在寻找该参数,因此您必须有点多余,并定义两次。

答案 4 :(得分:0)

如果您想抄送多个用户,那么在 djanogo 中使用 sendgrid 您需要导入以下行 enter image description here

将用于发送邮件的函数 enter image description here

最后你需要如何将数据参数发送到上述函数以便它可以抄送人

script: [
  { src: 'js/jquery-3.4.1.min.js' },
]
相关问题