如何使用Java中的SES和lambda通过电子邮件发送附件



我正在尝试使用java中的AWS SES和lambda通过电子邮件发送存储在s3中的文件。邮件已成功发送,但当我试图打开文件时出现错误";Excel无法打开文件"filename.xlsx",因为文件格式或文件扩展名无效。请验证文件是否已损坏,以及文件扩展名是否与文件的格式匹配">

java中的代码段:公共类电子邮件通知{

static LambdaLogger logger = null;
private static String SENDER=null;
private static String RECIPIENT=null;
private static String SUBJECT=null;
private static String BODY_TEXT=null;
private static String filekey=null;
public void verifyEmailNotification(Context context) throws Exception {
LambdaLogger logger = null;

try {
logger = context.getLogger();
String bucket_name = "bucket_name";
String key_name = "path/";
String file_name ="file_name.xlsx";
filekey = key_name + file_name;
AmazonS3 s3client = GetAWSClients.getS3();
boolean isFileExists=Utility.checkIfFileExists(bucket_name, filekey);
logger.log("isFileExists " + isFileExists);
if (isFileExists)
filekey = key_name + file_name;
else
logger.log("file not available");

InputStream stream = s3client.getObject(bucket_name, filekey).getObjectContent();
XSSFWorkbook workbook = new XSSFWorkbook(stream);

ByteArrayOutputStream bos = new ByteArrayOutputStream();
workbook.write(bos);
ByteArrayInputStream contentsAsStream = new ByteArrayInputStream(bos.toByteArray());
ObjectMetadata md = new ObjectMetadata();

md.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
md.setSSEAlgorithm(ObjectMetadata.AES_256_SERVER_SIDE_ENCRYPTION);
md.setContentLength(bos.toByteArray().length);

SENDER = "sender email";
RECIPIENT = "receiver email";
SUBJECT = "subject";
BODY_TEXT = "Body text";

Session session = Session.getDefaultInstance(new Properties());
MimeMessage message = new MimeMessage(session);
message.setSubject(SUBJECT);
message.setFrom(new InternetAddress(SENDER));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(RECIPIENT));
MimeMultipart msg_body = new MimeMultipart("alternative");
MimeBodyPart textPart = new MimeBodyPart();
textPart.setContent(BODY_TEXT, "text/plain; charset=UTF-8");
msg_body.addBodyPart(textPart);

MimeBodyPart att = new MimeBodyPart();
DataSource fds = new ByteArrayDataSource(bos.toByteArray(), "application/octet-stream");
att.setDataHandler(new DataHandler(fds));
att.setFileName(TemplateFile);
message.setContent(msg_body);
msg_body.addBodyPart(att);


try {
System.out.println("Attempting to send an email through Amazon SES "
+"using the AWS SDK for Java...");
AmazonSimpleEmailService client = GetAWSClients.getSES();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
message.writeTo(outputStream);
RawMessage rawMessage = new RawMessage(ByteBuffer.wrap(outputStream.toByteArray()));
SendRawEmailRequest rawEmailRequest = new SendRawEmailRequest(rawMessage);
client.sendRawEmail(rawEmailRequest);
System.out.println("Email sent!");
workbook.close();
} catch (Exception ex) {
System.out.println("Email Failed");
System.err.println("Error message: " + ex.getMessage());
ex.printStackTrace();
}
}
catch(Exception ex) {
System.out.println("Email Failed");
System.err.println("Error message: " + ex.getMessage());
ex.printStackTrace();
}
}

}

使用POI和工作簿概念并解决了问题。

public void verifyEmailNotification(Context context) throws IOException, MessagingException {
String bucketName = "bucketName";
String key = "prefix";
String fileName = "fileName.xlsx";
String keyName = key + fileName;
S3Object fullObject = null;
try {
SENDER = "sender email";
RECIPIENT = "receiver email";
SUBJECT = "Subject msg";
BODY_TEXT = "Hi";

logger = context.getLogger();
AmazonS3Client s3Client = (AmazonS3Client) AmazonS3ClientBuilder.defaultClient();
InputStream stream = s3Client.getObject(new GetObjectRequest(bucketName, keyName)).getObjectContent();
// Preparing input-stream as spreed sheet.
XSSFWorkbook workbook = new XSSFWorkbook(stream);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
workbook.write(bos);
logger.log("Read successn");
Session session = Session.getDefaultInstance(new Properties());
MimeMessage message = new MimeMessage(session);
message.setSubject(SUBJECT);
message.setFrom(new InternetAddress(SENDER));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(RECIPIENT));
MimeMultipart msg_body = new MimeMultipart("alternative");
MimeBodyPart textPart = new MimeBodyPart();
textPart.setContent(BODY_TEXT, "text/plain; charset=UTF-8");
msg_body.addBodyPart(textPart);
// Preparing the attachment from the spread sheet
MimeBodyPart att = new MimeBodyPart();
DataSource fds = new ByteArrayDataSource(bos.toByteArray(), "application/octet-stream");
att.setDataHandler(new DataHandler(fds));
att.setFileName(fileName);
msg_body.addBodyPart(att);
message.setContent(msg_body);
logger.log("attachment preparedn");
AmazonSimpleEmailServiceClientBuilder.standard().withRegion(Regions.US_EAST_1).build();
AmazonSimpleEmailService client = GetAWSClients.getSES();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
message.writeTo(outputStream);
RawMessage rawMessage = new RawMessage(ByteBuffer.wrap(outputStream.toByteArray()));
SendRawEmailRequest rawEmailRequest = new SendRawEmailRequest(rawMessage);
client.sendRawEmail(rawEmailRequest);
System.out.println("Email sent!");
} catch (AmazonServiceException e) {
// The call was transmitted successfully, but Amazon S3 couldn't process
// it, so it returned an error response.
e.printStackTrace();
} catch (SdkClientException e) {
// Amazon S3 couldn't be contacted for a response, or the client
// couldn't parse the response from Amazon S3.
e.printStackTrace();
}
}

相关内容

  • 没有找到相关文章

最新更新