我需要使用 sendgrid API 在 java 中发送带有附件的邮件。我提到了像[filename.xls]=bytearray
这样的文件.我正在使用 jxl API 获取这个字节数组。我能够发送邮件,但xls
没有值。
法典:
sendgridUrl+"?api_user="+apiUser + "&api_key=" + apiPassword + ""
+ to + "&subject=" + (subject.replaceAll(" ", "%20")) + "&fromname="
+ senderPersonal + "&files[" + fileName + "]=" + value2
+ "&html=" + message + "&from=" + AppConfig.getProperty("senderemail");
private static bool SendMailUsingSendgrid(EmailSendRequestDTO request)
{
try
{
string htmlContent = string.Empty;
string plainTextContent = string.Empty;
// Set apikey
var apiKey = ConfigReader.Read(CommonEnums.ConfigKeys.SendgridApiKey);
// Initialize sendgrid client.
var client = new SendGridClient(apiKey);
// From address
var from = new EmailAddress(request.FromAddress, request.FromDisplayName);
// Subject
var subject = request.Subject;
// Send mail to multiple recepients.
var recepientList = new List<EmailAddress>();
if (!string.IsNullOrEmpty(request.ToAddresses))
{
foreach (var toAddress in request.ToAddresses.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries))
{
recepientList.Add(new EmailAddress(toAddress));
}
}
// If content in html format
if (request.IsHtmlFormat)
{
htmlContent = request.Body;
}
else
{
plainTextContent = request.Body;
}
// Creat object to send mail message.
var mailMessage = MailHelper.CreateSingleEmailToMultipleRecipients(from, recepientList, subject, plainTextContent, htmlContent);
// add multiple cc.
var ccList = new List<EmailAddress>();
if (!string.IsNullOrEmpty(request.CCAddresses))
{
foreach (var ccAddress in request.CCAddresses.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries))
{
ccList.Add(new EmailAddress(ccAddress));
}
}
// add multiple bcc.
var bccList = new List<EmailAddress>();
if (!string.IsNullOrEmpty(request.BCCAddresses))
{
foreach (var bccAddress in request.BCCAddresses.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries))
{
bccList.Add(new EmailAddress(bccAddress));
}
}
// Attachments
if (!string.IsNullOrEmpty(request.AttachmentFile))
{
foreach (var attachmentFile in request.AttachmentFile.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries))
{
SendGrid.Helpers.Mail.Attachment messageAttachment = new SendGrid.Helpers.Mail.Attachment();
mailMessage.Attachments.Add(messageAttachment);
}
}
var response = client.SendEmailAsync(mailMessage).Result;
return true;
}
catch (Exception)
{
return false;
}
}