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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
Related
A file is being uploaded with Slack api from Spring boot app.
And I'm trying to add mention to user on channel like #username, but it is being printed as a plain text.
Is it possible to mention user in initialComment field of FilesUploadRequest?
#username and <#username> are both not working.
void slackTest () throws Exception {
Slack slack = new Slack();
List<String> channelList = new ArrayList<>();
channelList.add(MY_CHANNEL);
FilesUploadRequest.FilesUploadRequestBuilder req = FilesUploadRequest.builder();
req.token(MY_TOKEN);
req.channels(channelList);
req.title("test title");
req.content("test content");
req.initialComment("[test]\n\n#username\n\n<#username>"); // <- this is where the mention is needed.
FilesUploadResponse response = slack.methods(MY_TOKEN).filesUpload(req.build());
}
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();
I have a .Net Core MVC Web application that authenticates the user using AzureAD. At some stage I need to send an e-mail on behalf of that user.
I searched for some options and apparently I can do that using Microsoft Exchange Service or Office365 but for both options I need to get the user's credential.
An example using Office365 is below however I do not know how to user the signed in info to pass to the SMTP server.
My (partial) HomeController:
private readonly ClaimsPrincipal _principal;
public HomeController(IPrincipal principal){
_principal = principal as ClaimsPrincipal;
}
I can use _principal.FindFirst(ClaimTypes.Upn).Value to get the user's e-mail address but how do I get the password?
Am I in the right path or am I missing anything?
public static void SendEmail(string toAddress, string fromAddress, string subject, string content)
{
SmtpClient client = new SmtpClient();
client.Credentials = new NetworkCredential("", "");
client.Port = 587;
client.Host = "smtp.office365.com";
client.EnableSsl = true;
MailMessage newMail = new MailMessage();
newMail.To.Add(toAddress);
newMail.From = new MailAddress(fromAddress);
newMail.Subject = subject;
newMail.IsBodyHtml = true;
newMail.Body = "<html><body>" + content + "</body></html>";
client.Send(newMail);
}
I'm sorry if this is a broad question but I really need some light on how to achieve this. I'm happy to provide more details if necessary.
At some stage I need to send an e-mail on behalf of that user.
Per my understanding, you could use the cloud-based email service SendGrid to handle email delivery on behalf of your authenticated user's email address. The code for sending the email to test02#example.com for the user test01#example.com would look like this:
var client = new SendGridClient("<SendGrid-ApiKey>");
var msg = new SendGridMessage()
{
From = new EmailAddress("test01#example.com", "test01"),
Subject = "Hello World from the SendGrid CSharp SDK!",
PlainTextContent = "Hello, Email!",
HtmlContent = "<strong>Hello, Email!</strong>"
};
msg.AddTo(new EmailAddress("test02#example.com", "Test02"));
var response = await client.SendEmailAsync(msg);
Detailed tutorial, you could follow sendgrid-csharp.
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".
I will first show the code that works in a non-ssl (http) environment. This code uses a custom json error handler, and all errors thrown, do get bubbled up to the client javascript (ajax).
// Create webservice endpoint
WebHttpBinding binding = new WebHttpBinding();
ServiceEndpoint serviceEndPoint = new ServiceEndpoint(ContractDescription.GetContract(Type.GetType(svcHost.serviceContract + ", " + svcHost.assemblyName)), binding, new EndpointAddress(svcHost.hostUrl));
// Add exception handler
serviceEndPoint.Behaviors.Add(new FaultingWebHttpBehavior());
// Create host and add webservice endpoint
WebServiceHost webServiceHost = new WebServiceHost(svcHost.obj, new Uri(svcHost.hostUrl));
webServiceHost.Description.Endpoints.Add(serviceEndPoint);
webServiceHost.Open();
I'll also show you what the FaultingWebHttpBehavior class looks like:
public class FaultingWebHttpBehavior : WebHttpBehavior
{
public FaultingWebHttpBehavior()
{
}
protected override void AddServerErrorHandlers(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
{
endpointDispatcher.ChannelDispatcher.ErrorHandlers.Clear();
endpointDispatcher.ChannelDispatcher.ErrorHandlers.Add(new ErrorHandler());
}
public class ErrorHandler : IErrorHandler
{
public bool HandleError(Exception error)
{
return true;
}
public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
{
// Build an object to return a json serialized exception
GeneralFault generalFault = new GeneralFault();
generalFault.BaseType = "Exception";
generalFault.Type = error.GetType().ToString();
generalFault.Message = error.Message;
// Create the fault object to return to the client
fault = Message.CreateMessage(version, "", generalFault, new DataContractJsonSerializer(typeof(GeneralFault)));
WebBodyFormatMessageProperty wbf = new WebBodyFormatMessageProperty(WebContentFormat.Json);
fault.Properties.Add(WebBodyFormatMessageProperty.Name, wbf);
}
}
}
[DataContract]
public class GeneralFault
{
[DataMember]
public string BaseType;
[DataMember]
public string Type;
[DataMember]
public string Message;
}
The AddServerErrorHandlers() method gets called automatically, once webServiceHost.Open() gets called. This sets up the custom json error handler, and life is good :-)
The problem comes, when we switch to and SSL (https) environment. I'll now show you endpoint creation code for SSL:
// Create webservice endpoint
WebHttpBinding binding = new WebHttpBinding();
ServiceEndpoint serviceEndPoint = new ServiceEndpoint(ContractDescription.GetContract(Type.GetType(svcHost.serviceContract + ", " + svcHost.assemblyName)), binding, new EndpointAddress(svcHost.hostUrl));
// This exception handler code below (FaultingWebHttpBehavior) doesn't work with SSL communication for some reason, need to resarch...
// Add exception handler
serviceEndPoint.Behaviors.Add(new FaultingWebHttpBehavior());
//Add Https Endpoint
WebServiceHost webServiceHost = new WebServiceHost(svcHost.obj, new Uri(svcHost.hostUrl));
binding.Security.Mode = WebHttpSecurityMode.Transport;
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
webServiceHost.AddServiceEndpoint(svcHost.serviceContract, binding, string.Empty);
Now, with this SSL endpoint code, the service starts up correctly, and wcf hosted objects can be communicated with just fine via client javascript. However, the custom error handler doesn't work. The reason is, the AddServerErrorHandlers() method never gets called when webServiceHost.Open() is run.
So, can anyone tell me what is wrong with this picture? And why, is AddServerErrorHandlers() not getting called automatically, like it does when I'm using non-ssl endpoints?
Thanks!
I will refer you to MSDN docs
If the Transport value is specified by
the
WebHttpBinding(WebHttpSecurityMode),
then the settings provided by the
Transport property become effective
for the service endpoint. The value of
WebHttpSecurityMode can only be set in
the WebHttpBinding constructor that
takes it as an explicit parameter and
its value cannot be set again after
the binding instance is created.
see : http://msdn.microsoft.com/en-us/library/bb348328.aspx
So you need to pass this value
binding.Security.Mode = WebHttpSecurityMode.Transport;
into your .ctor() like that
WebHttpBinding binding = new WebHttpBinding(WebHttpSecurityMode.Transport);
I have never used this before as I always declare my bindings into web.config file but according to MSDN, this is what you should do.