如何使用SendGrid Api在单个电子邮件中发送多个附件?
问题描述:
我能够与单个附件发送电子邮件,但我不能在单个邮件如何使用SendGrid Api在单个电子邮件中发送多个附件?
try {
SendGrid sendgrid = new SendGrid(SENDGRID_USERNAME, SENDGRID_PASSWORD);
SendGrid.Email email = new SendGrid.Email();
// Get values from edit text to compose email
// TODO: Validate edit texts
email.addTo(mTo);
email.setFrom(mFrom);
email.setSubject(mSubject);
email.setText(mText);
// Attach image
if (mUri != null) {
email.addAttachment(mAttachmentName, mAppContext.getContentResolver().openInputStream(mUri));
}
// Send email, execute http request
SendGrid.Response response = sendgrid.send(email);
mMsgResponse = response.getMessage();
Log.d("SendAppExample", mMsgResponse);
} catch (SendGridException | IOException e) {
Log.e("SendAppExample", e.toString());
}
return null;
}
答
我假定您已经阅读此URL发送多个附件发现了什么:How to Send Email Using SendGrid with Azure
你将在这里找到一个项目的完整示例:sendgrid-csharp
更具体的添加多个附件:SendGridMessage.cs
这是我的代码修改:
-
从流增加附件创建方法
private static async Task AddAttachmentAsync(List<Attachment> ls, string filename, Stream contentStream, string type = null, string disposition = null, string content_id = null, CancellationToken cancellationToken = default(CancellationToken)) { // Stream doesn't want us to read it, can't do anything else here if (contentStream == null || !contentStream.CanRead) { return; } var contentLength = Convert.ToInt32(contentStream.Length); var streamBytes = new byte[contentLength]; await contentStream.ReadAsync(streamBytes, 0, contentLength, cancellationToken); var base64Content = Convert.ToBase64String(streamBytes); ls.Add(AddAttachment(filename, base64Content, type, disposition, content_id)); } private static Attachment AddAttachment(string filename, string base64Content, string type = null, string disposition = null, string content_id = null) { if (string.IsNullOrWhiteSpace(filename) || string.IsNullOrWhiteSpace(base64Content)) { return null; } var attachment = new Attachment { Filename = filename, Content = base64Content, Type = type, Disposition = disposition, ContentId = content_id }; return attachment; }
-
如何从数据流中添加附件SendGridMessage
//var msg = new SendGridMessage(); //your another settings addContent(body), subject, To etc //HttpFileCollection fuAttachment --> list attachments from http file collection //dont forget : msg.Attachments = new List<Attachment>(); for (var i = 0; i < fuAttachment.Count; i++) { string FileName = Path.GetFileName(fuAttachment[i].FileName); await AddAttachmentAsync(msg.Attachments, FileName, fuAttachment[i].InputStream); } //var apiKey = _SendGridAPIKey; //var client = new SendGridClient(apiKey); //var response = await client.SendEmailAsync(msg);
兄弟,我想在android中完成它。但我很感谢你的努力,谢谢你 –
哦,对不起,我没有看到..上面的代码是为asp.net:D 我应该删除这个? –
不需要老兄,也许它会帮助别人。 –