Я проверял всю документацию AWS, но не нашел никакого примера или текста, который может руководствовать «Как отправить электронную почту с вложением файла с использованием AWS SES (простая служба электронной почты) и Java?» Файл < /li>
Создайте файл, например abc.csv < /li>
Подготовьте тело электронной почты, добавьте это вложение и текст < /li>
Отправить его < /li>
< /ul>
Я следовал примерам ниже, это объясняет процесс что -то вроде этого:
Пример:
Источник изображения: http://www.codejava.net/java-ee/javamai ... nt-in-java> i-make with-atatchment-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();
}
< /code>
Не уверен, что именно мне здесь не хватает?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
Как отправить электронное письмо с вложением файла с помощью AWS SES и Java? ⇐ JAVA
Программисты JAVA общаются здесь
1758035220
Anonymous
Я проверял всю документацию AWS, но не нашел никакого примера или текста, который может руководствовать «Как отправить электронную почту с вложением файла с использованием AWS SES (простая служба электронной почты) и Java?» Файл < /li>
Создайте файл, например abc.csv < /li>
Подготовьте тело электронной почты, добавьте это вложение и текст < /li>
Отправить его < /li>
< /ul>
Я следовал примерам ниже, это объясняет процесс что -то вроде этого:
Пример:
Источник изображения: http://www.codejava.net/java-ee/javamail/send-e-mail-with-attachment-in-java> i-make with-atatchment-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/05/example-of-sding-email-with-multipal.html
Но я не понял:
DataSource source = new FileDataSource(filename);
attachment.setDataHandler(new DataHandler(source));
[b] Как я могу определить источник, если я готовлю файл на той же функции [/b], например,
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();
}
< /code>
Не уверен, что именно мне здесь не хватает?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[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";
}
}
Подробнее здесь: [url]https://stackoverflow.com/questions/39533430/how-to-send-email-with-a-file-attachment-using-aws-ses-and-java[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия