我检查了所有 Aws 文档, 但没有找到任何实例或文字, 可以指导“ 如何使用 aws ses( 简单的电子邮件服务) 和 java 发送带有文件附件的电子邮件 ”?
我需要写出符合逻辑的文字:
- Receive a set of data
- convert this data to CSV file
- Create a file e.g. abc.csv
- Prepare a email body, add this attachment and text
- Send it
I have followed below examples, these explains the process something like this:
Example:
Image Source: http://www.codejava.net/java-ee/javamail/send-e-mail-with-attachment-in-java
我听了这个答案 ,但不明白这部分:
//Attachment part
if (attachment != null && attachment.length != 0)
{
messageBodyPart = new MimeBodyPart();
DataSource source = new ByteArrayDataSource(attachment,fileMimeType);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(fileName);
multipart.addBodyPart(messageBodyPart);
}
msg.setContent(multipart);
这个例子也跟随了这个例子:https://mintylishjava.blogspot.in/2014/05/example-of-sending-email-with-mulpal.html 。
但我不明白:
DataSource source = new FileDataSource(filename);
attachment.setDataHandler(new DataHandler(source));
< 加固> 如何定义源, 如果我正在准备一个相同函数 加固 > 的文件, 例如 。
File myFile = new File("TestFile_"+ LocalDateTime.now().toString()+ ".csv");
try {
fop = new FileOutputStream(myFile);
byte[] contentInBytes = textBody.getData().getBytes();
fop.write(contentInBytes);
fop.flush();
fop.close();
} catch (java.io.IOException e) {
e.printStackTrace();
}
无法确定我到底错过了什么? < / 坚固>
Solved
public String sendReceivedOutputAsEmailToUsers(EmailProperties emailProperties,String fileContents , String toEmails) throws InternalErrorException
{
String[] toAddressesInput = null;
// Get the toArrays
toAddressesInput = toEmails.split(",");
BasicAWSCredentials basicAWSCredentials = new BasicAWSCredentials(PropertyManager.getSetting("awsAccessKeyId"),
PropertyManager.getSetting("awsSecretAccessKey"));
// Construct an object to contain the recipient address.
Destination destination = new Destination().withToAddresses(toAddressesInput);
// Create the subject and body of the message.
// emailRequest.getSubject() - need to write the format of message
// Prepare Subject
String subject = CommonStrings.defaultSubject + " Generated at: " + LocalDateTime.now().toString();
if(emailProperties.getSubject()!=null)
{
subject = emailProperties.getSubject() + " Generated at: " + LocalDateTime.now().toString();;
}
String inputFileName = null;
if(emailProperties.getAttachmentName() != null)
{
inputFileName = emailProperties.getAttachmentName() + "_" + LocalDateTime.now().toString() + ".csv";
}else
{
inputFileName = "GenreatedReport__" + LocalDateTime.now().toString() + ".csv";
}
Content textBody = null;
FileOutputStream fop = null;
if(emailProperties.getIsBody().equalsIgnoreCase("true"))
{
if(emailProperties.getBodyMessagePrefix()!= null) {
textBody = new Content().withData("
" + emailProperties.getBodyMessagePrefix() + "
" +fileContents);
} else
{
textBody = new Content().withData("
" +fileContents);
}
}
AmazonSimpleEmailServiceClient client = null;
client = new AmazonSimpleEmailServiceClient(basicAWSCredentials);
Properties props = new Properties();
// sets SMTP server properties
props.setProperty("mail.transport.protocol", "aws");
props.setProperty("mail.aws.user", PropertyManager.getSetting("awsAccessKeyId"));
props.setProperty("mail.aws.password", PropertyManager.getSetting("awsSecretAccessKey"));
Session mailSession = Session.getInstance(props);
// Create an email
MimeMessage msg = new MimeMessage(mailSession);
// Sender and recipient
try {
msg.setFrom(new InternetAddress(CommonStrings.adminEmailAddress));
} catch (MessagingException e) {
throw new InternalErrorException(ExceptionStrings.EX_EMAIL + ":" + e.getMessage());
}
// msg.setRecipient( Message.RecipientType.TO, new InternetAddress("abc <[email protected]>"));
// for multiple Recipient
InternetAddress[] toAddresses = new InternetAddress[toAddressesInput.length];
for (int i = 0; i < toAddresses.length; i++)
{
try {
toAddresses[i] = new InternetAddress(toAddressesInput[i]);
} catch (AddressException e) {
throw new InternalErrorException(ExceptionStrings.EX_EMAIL + ":" + e.getMessage());
}
}
try {
msg.setRecipients(javax.mail.Message.RecipientType.TO, toAddresses);
msg.setSubject(subject);
} catch (MessagingException e) {
throw new InternalErrorException(ExceptionStrings.EX_EMAIL + ":" + e.getMessage());
}
// creates message part
BodyPart part = new MimeBodyPart();
try {
part.setContent(textBody.getData(), "text/html");
} catch (MessagingException e) {
throw new InternalErrorException(ExceptionStrings.EX_EMAIL + ":" + e.getMessage());
}
// Add a MIME part to the message
MimeMultipart mp = new MimeMultipart();
try {
mp.addBodyPart(part);
} catch (MessagingException e) {
throw new InternalErrorException(ExceptionStrings.EX_EMAIL + ":" + e.getMessage());
}
BodyPart attachment = null;
attachment = new MimeBodyPart();
try {
DataSource source = new FileDataSource(fileContents);
attachment.setDataHandler(new DataHandler(source));
attachment.setText(fileContents);
attachment.setFileName(inputFileName);
mp.addBodyPart(attachment);
msg.setContent(mp);
} catch (MessagingException e) {
throw new InternalErrorException(ExceptionStrings.EX_EMAIL + ":" + e.getMessage());
}
// Print the raw email content on the console
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
msg.writeTo(out);
} catch (IOException e) {
throw new InternalErrorException(ExceptionStrings.EX_EMAIL + ":" + e.getMessage());
} catch (MessagingException e) {
throw new InternalErrorException(ExceptionStrings.EX_EMAIL + ":" + e.getMessage());
}
// Send Mail
RawMessage rm = new RawMessage();
rm.setData(ByteBuffer.wrap(out.toString().getBytes()));
client.sendRawEmail(new SendRawEmailRequest().withRawMessage(rm));
logger.info("email sent : success");
return "success";
}
}