- Получить набор данных
- преобразовать эти данные в файл CSV
- Создайте файл, например. abc.csv
- Подготовьте тело электронного письма, добавьте вложение и текст
- Отправьте
Пример:

Источник изображения: http://www.codejava.net/java-ee/javamai ... t-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://mintylikejava.blogspot.in/2014/ ... tipal.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();
}
Не уверен, что именно мне здесь не хватает?
Решено
Ниже функция, которую я написал для решения этой проблемы (добавлено 29 декабря 2016 г.):
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("\n\n" + emailProperties.getBodyMessagePrefix() + "\n\n" +fileContents);
} else
{
textBody = new Content().withData("\n\n" +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 "));
// for multiple Recipient
InternetAddress[] toAddresses = new InternetAddress[toAddressesInput.length];
for (int i = 0; i < toAddresses.length; i++)
{
try {
toAddresses = new InternetAddress(toAddressesInput);
} 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";
}
}
Подробнее здесь: https://stackoverflow.com/questions/395 ... s-and-java