How can attachment names be retrieved from a JavaMailSender exception? - spring

I'm using org.springframework.mail.javamail.JavaMailSender (Spring Framework 4.1.6). I'm sending multiple emails by calling:
mailSender.send(mimeMessagePreparators);
where mimeMessagePreparators is a MimeMessagePreparator array. Each MimeMessagePreparator is built as follows:
MimeMessagePreparator mimeMessagePreparator = new MimeMessagePreparator() {
public void prepare(MimeMessage mimeMessage) throws MessagingException {
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
// get the subscribers of the attachment and put them as the recipients
// of this email
mimeMessageHelper.setTo(subscribers);
// all email have the same from, bcc, reply to, subject, and body
String fromEmailAddress = emailTemplate.getFromEmailAddress();
mimeMessageHelper.setFrom(fromEmailAddress);
// note: bcc the sender so that they get the email too
mimeMessageHelper.setBcc(fromEmailAddress);
// this will help on auto replies and bounce messages
// also it should help on deliverability
mimeMessageHelper.setReplyTo(fromEmailAddress);
String subject = emailTemplate.getSubject();
mimeMessageHelper.setSubject(subject);
String emailBody = emailTemplate.getBody();
mimeMessageHelper.setText(OPEN_EMAIL_TAGS + emailBody + CLOSE_EMAIL_TAGS, true);
// get the physical file and add as an email attachment
FileSystemResource file = new FileSystemResource(new File(directory, attachment.getName()));
mimeMessageHelper.addAttachment(attachment.getName(), file);
}
};
I need to know which emails failed (i.e. had a MailException) and eventually tell the user the names of the attachments associated with emails that failed. How can I retrieve the attachment names from the exception? So far, I have
try {
mailSender.send(mimeMessagePreparators);
} catch (MailSendException mailSendException) {
Map<Object, Exception> map = mailSendException.getFailedMessages();
for (Map.Entry<Object, Exception> entry : map.entrySet()) {
MimeMessage mimeMessage = (MimeMessage) entry.getKey();
// get attachment names from mimeMessage? or preferably
// get in a more simplistic way using a helper such as MimeMessageHelper
} catch (MailException mailException) {
// how do I get attachment names here?
}

If you have a bunch of MimeMessage objects, see the JavaMail FAQ entries starting here:
How do I tell if a message has attachments?
Essentially, you need to iterate over the parts in the message, determine which ones represent attachments, and then access whatever metadata or headers in the part you think represent the attachment "name".

Related

How to change the from address in send grid email

I have configured the send grid API for email service in my spring boot APP. And, it's working fine. I wanted to change the from address as "no-reply#xyz.com" instead of "apikey". But, I couldn't.
Also, I tried it using JavaMaiSender. But, no luck.
Could you please anyone let me know?
public void sendEmailUsingSendgrid(EmailRequest emailRequest) throws IOException {
String text = getEmailTemplate(emailRequest);
SendGrid sg = new SendGrid(sendGridApi);
sg.addRequestHeader("X-Mock", "true");
Request request = new Request();
Mail mail = new Mail();
mail.setFrom(new Email(emailRequest.getFr()));
mail.setSubject(emailRequest.getSbjt());
mail.addContent(new Content("text/html", text));
List<String> mailList = Arrays.asList(emailRequest.getTo());
for (String to : mailList) {
Personalization p1 = new Personalization();
p1.addTo(new Email(to));
mail.addPersonalization(p1);
}
mail.setReplyTo(new Email("noreply#xyz.com"));
request.setMethod(Method.POST);
request.setEndpoint("mail/send");
request.setBody(mail.build());
sg.api(request);
}
Properties
# SENDGRID
sendgrid-api-key=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

Send a mail with an attachment on my hard drive with Apache commons email

I have a problem to send an attachment in my mail with Apache commons email.
To explain it quick and dirty, the mail is sent but there is no attachment at all when i look at it in Outlook.
I use Apache commons email v1.4 and JAVA 8.
I want to add a log file which is on my hard drive at this location C:\myfolder\myfile.log
This is what i have tried so far to add the attachment
Path logRejetPath = Paths.get("C:\\myfolder\\myfile.log");
Boolean pathExists = Files.exists(logRejetPath, new LinkOption[]{LinkOption.NOFOLLOW_LINKS});
if (pathExists) {
File rejLogFile = new File(logRejetPath.toString());
email.attach(new FileDataSource(rejLogFile), "test", "test");
}
email.send();
Or
Path logRejetPath = Paths.get("C:\\myfolder\\myfile.log");
Boolean pathExists = Files.exists(logRejetPath, new LinkOption[]{LinkOption.NOFOLLOW_LINKS});
if (pathExists) {
File rejLogFile = new File(logRejetPath.toString());
email.attach(rejLogFile);
}
email.send();
Or
Path logRejetPath = Paths.get("C:\\myfolder\\myfile.log");
Boolean pathExists = Files.exists(logRejetPath, new LinkOption[]{LinkOption.NOFOLLOW_LINKS});
if (pathExists) {
EmailAttachment attachment = new EmailAttachment();
attachment.setPath(logRejetPath.toString());
attachment.setDisposition(EmailAttachment.ATTACHMENT);
attachment.setDescription("test");
attachment.setName("test");
email.attach(attachment);
}
email.send();
I precise email is a MultiPartEmail object created like this:
MultiPartEmail email = new MultiPartEmail();
try {
email.setHostName(config.getSmtpHost());
email.setSmtpPort(Integer.valueOf(config.getSmtpPort()));
if (!config.getSmtpUser().isEmpty()) {
email.setAuthenticator(
new DefaultAuthenticator(config.getSmtpUser(), config.getSmtpPwd()));
email.setSSLOnConnect(true);
} else {
email.setSSLOnConnect(false);
}
email.setCharset("utf-8");
email.setFrom("me#me.fr");
email.setSubject("subjectforemail");
email.setContent(this.getMessage(), "text/html");
final String[] destinataires = config.getMailDestinataires().split(";");
for (final String dest : destinataires) {
email.addTo(dest);
}
Every time with these different methods to add an attachment, i receive my email with the message but without the attachment. Every time, variable pathExists is TRUE and every times i have no error.
Thanks for your future answers and help.
EDIT : Solution found by changing this :
MultiPartEmail email = new MultiPartEmail();
by this :
HtmlEmail email = new HtmlEmail();
Solution found by changing this :
MultiPartEmail email = new MultiPartEmail();
by this :
HtmlEmail email = new HtmlEmail();

Can't able to send SMS using Twilio Trail Account using C#

I'm just trying to use Twilio to send transaction SMS. I have tried exactly the same code which is provided in the Twilio Documentation
static void Main(string[] args)
{
try
{
// Find your Account Sid and Token at twilio.com/console
const string accountSid = "AC5270abb139629daeb8f3c205ec632155";
const string authToken = "XXXXXXXXXXXXXX";
TwilioClient.Init(accountSid, authToken);
var message = MessageResource.Create(
from: new Twilio.Types.PhoneNumber("+15017122661"),
body: "Body",
to: new Twilio.Types.PhoneNumber("MyNumber")
);
Console.WriteLine(message.Sid);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
in this authToken copy from Twilio console and the TO number is my number which is used to register on Twilio. I also have verified the number in Verified Caller IDs segment in Twilio Console.
From Number initially, I was using the number which is generated by in Twilio Console the Number Belongs to the US but it won't work. After Reading this
Article I used the Exact code provided by Twilio just make the Changes as authToken and TO Number. But still, it won't work.
I have No idea why it Does not Work. is that you Can't Send the message from one country to another country?
As I want to Verify Mobile number by sending code from SMS. so achieve this I'm using
Twilio Verify API here where the Code is generated by Twilio and verified by himself.
this Solve my problem.
TO Send SMS :-
var client = new HttpClient();
var requestContent = new FormUrlEncodedContent(new[] {
new KeyValuePair<string,string>("via", "sms"),
new KeyValuePair<string,string>("phone_number", "Moblienumber"),
new KeyValuePair<string,string>("country_code", "CountryCode"),
});
// https://api.authy.com/protected/$AUTHY_API_FORMAT/phones/verification/start?via=$VIA&country_code=$USER_COUNTRY&phone_number=$USER_PHONE
HttpResponseMessage response = await client.PostAsync(
"https://api.authy.com/protected/json/phones/verification/start?api_key=" + "Your Key",
requestContent);
// Get the response content.
HttpContent responseContent = response.Content;
// Get the stream of the content.
using (var reader = new StreamReader(await responseContent.ReadAsStreamAsync()))
{
// Write the output.
Console.WriteLine(await reader.ReadToEndAsync());
}
return Ok();
To Verify :-
// Create client
var client = new HttpClient();
// Add authentication header
client.DefaultRequestHeaders.Add("X-Authy-API-Key", "Your Key");
// https://api.authy.com/protected/$AUTHY_API_FORMAT/phones/verification/check?phone_number=$USER_PHONE&country_code=$USER_COUNTRY&verification_code=$VERIFY_CODE
HttpResponseMessage response = await client.GetAsync(
"https://api.authy.com/protected/json/phones/verification/check?phone_number=phone_number&country_code=country_code&verification_code=CodeReceivedbySMS ");
// Get the response content.
HttpContent responseContent = response.Content;
// Get the stream of the content.
using (var reader = new StreamReader(await responseContent.ReadAsStreamAsync()))
{
// Write the output.
Console.WriteLine(await reader.ReadToEndAsync());
}
return Ok();

Send Status code and message in SpringMVC

I have the following code in my web application:
#ExceptionHandler(InstanceNotFoundException.class)
#ResponseStatus(HttpStatus.NO_CONTENT)
public ModelAndView instanceNotFoundException(InstanceNotFoundException e) {
return returnErrorPage(message, e);
}
Is it possible to also append a status message to the response? I need to add some additional semantics for my errors, like in the case of the snippet I posted I would like to append which class was the element of which the instance was not found.
Is this even possible?
EDIT: I tried this:
#ResponseStatus(value=HttpStatus.NO_CONTENT, reason="My message")
But then when I try to get this message in the client, it's not set.
URL u = new URL ( url);
HttpURLConnection huc = (HttpURLConnection) u.openConnection();
huc.setRequestMethod("GET");
HttpURLConnection.setFollowRedirects(true);
huc.connect();
final int code = huc.getResponseCode();
String message = huc.getResponseMessage();
Turns out I needed to activate custom messages on Tomcat using this parameter:
-Dorg.apache.coyote.USE_CUSTOM_STATUS_MSG_IN_HEADER=true
The message can be in the body rather than in header. Similar to a successful method, set the response (text, json, xml..) to be returned, but set the http status to an error value. I have found that to be more useful than the custom message in header. The following example shows the response with a custom header and a message in body. A ModelAndView that take to another page will also be conceptually similar.
#ExceptionHandler(InstanceNotFoundException.class)
public ResponseEntity<String> handle() {
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.set("ACustomHttpHeader", "The custom value");
return new ResponseEntity<String>("the error message", responseHeaders, HttpStatus.INTERNAL_SERVER_ERROR);
}

How to send email with attachments

I want to send an email with an image attached with it. I am using spring 3 with velocity templates. I am able to do that but for some reasons when I add an extension with the image name I don't get the email delivered.
Following is the code I am using for it:
private MimeMessage createEmail(Application application, String templatePath, String subject, String toEmail, String fromEmail, String fromName) {
MimeMessage mimeMsg = mailSender.createMimeMessage();
Map<String, Object> model = new HashMap<String, Object>();
model.put("application", application);
String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, templatePath, model);
text = text.replaceAll("\n", "<br>");
try {
MimeMessageHelper helper = new MimeMessageHelper(mimeMsg, true);
helper.setSubject(subject);
helper.setTo(toEmail);
if (fromName == null) {
helper.setFrom(fromEmail);
} else {
try {
helper.setFrom(fromEmail, fromName);
} catch (UnsupportedEncodingException e) {
helper.setFrom(fromEmail);
}
}
helper.setSentDate(application.getDateCreated());
helper.setText(text, true);
InputStream inputStream = servletContext.getResourceAsStream("images/formstack1.jpg");
helper.addAttachment("formstack1", new ByteArrayResource(IOUtils.toByteArray(inputStream)));
} catch (MessagingException e) {
throw new RuntimeException(e);
}
catch (IOException e) {
throw new RuntimeException(e);
}
return mimeMsg;
}
Using the code above I could add formstack1 as attachment but it has no extension so I don't get the formstack1.jpg image file. But when I use formstack1.jpg for the name of resource to be attached in helper.addAttachment("formstack1", new ByteArrayResource(IOUtils.toByteArray(inputStream))); as formstack1 changed to formstack1.jpg I don't get even the email delivered. I am using smtp.gmail.com and 25 for port. I do get the email sent successfully message on the console though. But the email
is never delivered.
EDIT: If I keep it like helper.addAttachment("formstack1", new ByteArrayResource(IOUtils.toByteArray(inputStream))); and change the extension from nothing to .jpg while downloading the attached image I do get the desired image.
Could someone help me understand why is it happening and how send email with 1 or more attachments using spring 3.
Thanks.
You should better use Apache Commons HtmlEMail
http://commons.apache.org/email/userguide.html

Resources