JavaMailSender SMTP Bounce back - Different domain email address - spring

I'm using the Spring java mailer class to send email messages to my users:
org.springframework.mail.javamail.JavaMailSenderImpl version 1.4 using Spring framework 3.0.7.RELEASE.
I want to set the bounce back message for a failed email to go to my user's email address that doesn't have the same domain as my smtp server. Does anyone know a way to accomplish this?
For example:
My system sends an email to email-does-not-exist#gmail.com. My smtp server is configured to have a domain somebusiness.com. Upon failure, send the bounceback to my user: test.user#gmail.com.
I read the following article several times:
Specifying the bounce-back address for email
I tried to use their method of setting the mail.smtp.from property but it won't send any emails at all (not even counting bounceback attempts from invalid emails yet).
Properties p = new Properties();
p.put("mail.smtp.from", "test.user#gmail.com"); //If I comment this out, it sends emails again
mailSender.setJavaMailProperties(p);
Session session = Session.getDefaultInstance(p, null);
MimeMessage mimeMessage = new MimeMessage(session);
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,
false, "utf-8");
mimeMessage.setContent(emailBody, "text/html");
helper.setTo(toAddress);
helper.setSubject(subject);
helper.setFrom(fromAddress);
mailSender.send(mimeMessage);
Anyone have an idea of why? The obvious answer seems like the smtp server we are using is blocking it but I was hoping for potential other ideas.

I'm having a similar problem. I don't have a solution yet, but at the moment I am considering replacing Spring's mail package with org.apache.commons.mail because it has a simple setBounceAddress(emailAddressString) method.
See the very end section "Handling Bounced Messages" of the user guide:
http://commons.apache.org/proper/commons-email//userguide.html
And the API docs:
http://commons.apache.org/proper/commons-email//apidocs/org/apache/commons/mail/Email.html#setBounceAddress(java.lang.String)

I just checked how the Apache Commons Mail implements it's bounce functionality and it actually just sets the from address. It means that you can do the same in Spring Mail by setFrom(...) on a org.springframework.mail.javamail.MimeMessageHelper class.
Source code snippet from org.apache.commons.mail.Email class:
if (this.bounceAddress != null) {
properties.setProperty(MAIL_SMTP_FROM, this.bounceAddress);
}
See it in the sources:
http://grepcode.com/file/repo1.maven.org/maven2/org.apache.commons/commons-email/1.2/org/apache/commons/mail/Email.java#539

Related

Laravel mailbox inbound parse sendgrid

So I'm trying to make my own inbox for emails using the followin packag beyondcode/laravel-mailbox
I installed the package on a blank project, in order to test it out.
I can send emails with the sendgrid API, so that's not a problem at all.
Now, I have some environment variables set;
MAILBOX_DRIVER=sendgrid
MAILBOX_HTTP_USERNAME=laravel-mailbox
MAILBOX_HTTP_PASSWORD=secret
The config just the same as given in the package.
In my AppServiceProvider, I have in the boot the following:
Mailbox::catchAll(static function(InboundEmail $email) {
// Handle the incoming email
Log::info('#-------------------------------------------------------------------------------------------#');
Log::info($email);
Log::info('#-------------------------------------------------------------------------------------------#');
});
But when I take a look in the logs, when I send an email to whatever#rallypodium.be, nothing hapens...
This is my DNS configuration:
And here is the inbound parse config on the sendgrid side:
What am I missing or doing wrong here? I looked at my access logs and not even a request is being made to the server from sendgrid...
So How can I make sure I can receive messages to whatever#mydomain.com?
Your DNS should also have a few CNAME records so that you can verify your domain with SendGrid.

Using EWS API send email method get 401 unauthorized

I'm very new to EWS API. Now I've a problem when I Send Email using EWS sample. Still getting the error:
401 unauthorized.
Here is my sample code:
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
service.Credentials = new WebCredentials("user1#contoso.com", "password");
service.TraceEnabled = true;
service.TraceFlags = TraceFlags.All;
service.AutodiscoverUrl("user1#contoso.com", RedirectionUrlValidationCallback);
EmailMessage email = new EmailMessage(service);
email.ToRecipients.Add("user1#contoso.com");
email.Subject = "HelloWorld";
email.Body = new MessageBody("This is the first email I've sent by using the EWS Managed API");
email.Send();
The error in the email.Send() function. Any help for this?
Related link:https://learn.microsoft.com/en-us/exchange/client-developer/exchange-web-services/get-started-with-ews-managed-api-client-applications
I searched all links but no correct answer.
I've checked your provide link and not found any problem. In general, There is no problem in writing this way. The problem should be related to your server environment or account as wannadream mentioned.
You can refer to the following links:
"(401) Unauthorized" error when you use an EWS application to impersonate a user in Office365 Dedicated/ITAR
Exchange Web Service API and 401 unauthorized exception
Also, could you please change your account to test it?
Shot in the dark, but easy to try: several years ago I was getting unexplained 401s, and found some web post that mentioned adding an empty cookie container to the service object, i.e.:
service.CookieContainer = new CookieContainer();
It seemed to do the trick at the time, but not sure if it's still a thing.

How client and server mapping message on Spring boot websocket

I cloned a chat application project that uses spring boot websocket on github.
Here is code:
#MessageMapping("/chat.private.{username}")
public void filterPrivateMessage(#Payload ChatMessage message, #DestinationVariable("username") String username, Principal principal) {
message.setUsername(principal.getName());
simpMessagingTemplate.convertAndSend("/user/" + username + "/exchange/amq.direct/chat.message", message);
}
Example: username variable is: foo#gmail.com, it mean the link to for client subscribe should be: /user/foo#gmail.com/exchange/amq.direct/chat.message
But in client code:
chatSocket = Stomp.over(new SockJS(url)); //use sockjs and stompjs
chatSocket.subscribe("/user/exchange/amq.direct/chat.message"
I do not understand how to the application can send to correct client, when the client listen the different url (without foo#gmail.com).
Can someone explain to me?
Thanks.
The key is the /user/ prefix in the subscribe url, which will be transformed by Spring to deliver the message to the specific user. It is described in the User Destinations section in the docs:
An application can send messages targeting a specific user, and Spring’s STOMP support recognizes destinations prefixed with /user/ for this purpose. For example, a client might subscribe to the destination /user/queue/position-updates. This destination will be handled by the UserDestinationMessageHandler and transformed into a destination unique to the user session, e.g. /queue/position-updates-user123. This provides the convenience of subscribing to a generically named destination while at the same time ensuring no collisions with other users subscribing to the same destination so that each user can receive unique stock position updates.

Spring 4 STOMP not sending queue-suffix in header on connect

I wrote a small project that uses Spring MVC 4 with Websockets and RabbitMQ as the broker.
I am trying to send back to a single user (convertAndSendToUser) but I can't seem to have it working. Here is what the application does:
authenticate to Spring Security over HTTP. The authentication is over AJAX and the backend assigns a UUID as the username to every new connection. There might be multiple clients with the same username so I would like to be able to target individual browsers although they may be logged in with the same username
after authenticating over AJAX the webapp connects to the APIs using STOMP over Websockets.
These are the headers that get send back in the CONNECT FRAME
body: ""
command: "CONNECTED"
headers: Object
heart-beat: "0,0"
server: "RabbitMQ/3.3.1"
session: "session-OGzAN6T8Y0X9ft3Jq04fiQ"
user-name: "88dc9424-72e3-4814-be8c-e31dbf89b521"
version: "1.1"
As you can see there is no frame-suffix or session-id field.
When I use convertAndSendToUser from the backend, the response is send to a unique queue like: /exchange/jobs-userh6g_48h9. The queue name is /exchange/jobs but Spring automatically attaches the suffix -userh6g_48h9. The username is "user" and the sessionId is "h6g_48h9" This is fine and I want this behavior but the problem is that the client (webapp) doesn't get this session id in the CONNECT frame and there is no way for it to actually subscribe to that unique queue.
How to solve this? I want the queue-suffix/session id sent back to me on connect so that the client can get this suffix and subscribe to his unique queues. Currently no messages come back from the server because of this lack of information.
Correct me if I'm wrong, but due to the UserDestinationMessageHandler, clients should be able to subscribe to /user/exchange/jobs and that message handler will correct the queue name for you.
As a side note, you should also consider adding a configuration class extending AbstractSecurityWebSocketMessageBrokerConfigurer similar to the following:
#Configuration
public class WebSocketSecurityConfig extends AbstractSecurityWebSocketMessageBrokerConfigurer {
#Override
protected void configureInbound(MessageSecurityMetadataSourceRegistry messages) {
messages
.antMatchers(SimpMessageType.MESSAGE, "/topic/**", "/queue/**").denyAll() // Prevent users sending messages directly to topics and queues
.antMatchers(SimpMessageType.SUBSCRIBE, "/queue/**/*-user*", "/topic/**/*-user*").denyAll() // Prevent users from subscriptions to private queues
.antMatchers("/user/queue/errors").permitAll()
.anyMessage().hasRole("ANY_OPTIONAL_ROLE_ETC")
;
}
}
This will prevent "enterprising" users from subscribing to things that they shouldn't.

Spring mail MimeMessage has an incorrect "From " set

I am using spring mail to send an email via google's smptp server. I am setting my email templates "From" header but for some reason when I do receive the mail as a sender I get the owner of the smtp account. (which happens to be me again).
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message);
helper.setText(forgottenPassowrdMailTemplate.getText()
.replace("%firstName%", token.getUser().getFirstName())
.replace("%lastName%", token.getUser().getLastName())
.replace("%link%", url + token.getToken()), true);
helper.setTo(token.getUser().getEmail());
helper.setFrom(forgottenPassowrdMailTemplate.getFrom());
helper.setSubject(forgottenPassowrdMailTemplate.getSubject());
am I forgetting something ? I a am explicitly setting the "From" header
You are setting a from address that is different from the account's address. There are security measures by Google to avoid abuse, which could be fatal if you could just send with any arbitrary from address via Google's SMTP server. You need to link and verify your other account with the account you want to send the mail with. See here. Your original email address will still be available in the headers and visible to the receipient.
But why don't you just use the other accounts credentials (and mail server, if it is not a Google account)?

Resources