Java Mail is it possible to show users email in from field? - java

I am creating a contact form and was wondering if it is possible to show the user's email in the "from "field in a contact email box. I am using java mail api.
Now it looks like this
can I show users' emails instead of grazerteamroma#gmail.com?
It seems like a can`t get access to a user's to account to send the mail from their account, am I right?

Not possible to set the sender address without the email server/provider.
Try replyTo Field in your code.
you can try replyTo of MimeMessage class.
Here is the spring version MimeMessageHelper class, you can set it using MimeMessage also.
public void sendEmail(Mail mail)
{
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
try {
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
mimeMessageHelper.setSubject(mail.getMailSubject());
mimeMessageHelper.setFrom(new InternetAddress(mail.getMailFrom()));
mimeMessageHelper.setTo(mail.getMailTo());
mimeMessageHelper.setText(mail.getMailContent());
mimeMessageHelper.setReplyTo(new InternetAddress("anupamXXXX#gmail.com"));
javaMailSender.send(mimeMessageHelper.getMimeMessage());
}
catch (MessagingException e) {
e.printStackTrace();
}
}
Using above code receiver will receive with replyto address on which he directly reply.

Java Mail is an API to talk to the backend (Mail User Agent to Mail Transport Agent communication). It is not related to presenting the mails to users at all.
So of course it is possible to users' email on the screen, be it the sender, the recipient or else. But this is a UI rendering issue, not Java Mail.
In other words: You are barking up the wrong tree.
But since you are asking:
Send email - here are examples
Receive email - here are examples
In case your question is just about how Google Mail can print the name of the recipient independently of the email address, it probably parses this (recipient/originator) string:
Alfred Neuman <Neuman#BBN-TENEXA>
See the specification for email messages: https://www.w3.org/Protocols/rfc822/#z10

Related

How to send emails from different accounts through JavaMailSender (w/o user login)

I have a Contact Us form on my webpage where a user can enter their name, email address and a message to send me an email. However I do not have the user logged into their mailing account. Is it possible to generate and send an e-mail through their mailing account without logging in?
On the back-end, when I set the value for the From Email, it is ignored and the email address used for sending the email is redacted#gmail.com
MailSender.java
#Autowired
private JavaMailSender mailSender;
public void sendEmail(String fromEmail, String body, String subject) throws MessagingException{
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true);
message.setFrom(fromEmail);
message.setTo("redacted#gmail.com");
message.setText(body);
message.setSubject(subject);
message.setSentDate(new Date());
mailSender.send(mimeMessage);
System.out.println("Mail sent successfully");
}
application.yaml
spring:
mail:
host: "smtp.gmail.com"
port: 587
username: redacted#gmail.com
password: redacted
properties:
mail:
smtp:
auth: true
starttls:
enable: true
required: true
The from part isn't your actual username or mail address. It's just the "display name" for the recipient.
Depending on the mail provider the from part must be identical to your username. In other cases it's fine to send mails with an arbitrary from. But most providers will reject this, because it can be a security risk for the receiver if they for example receive a mail from you, but their mail application shows support#microsoft.com. ;)
The from part also can be used to add a real name in addition to the mail address which requires a special format (something like My Name<redacted#gmail.com>). In Java this can be done like this:
message.setFrom(new InternetAddress("redacted#gmail.com", "My Name"));
But this again is highly dependent on your mail provider. Some will set this automatically for you. Some will require that it's identical to your user account data. And some will let you send whatever you want.
Btw: The same applies to sentDate. I don't think that Google allows you to provide a custom date, instead they will override it.

Cannot send email without authentication required

I wrote a simple Java program that uses Java Mail API to send an email.
public static void main(String[] args) {
System.out.println("SimpleEmail Start");
String smtpHostServer = "smtp.gmail.com";
String emailID = "xxxxxx#hotmail.com";
Properties props = System.getProperties();
props.put("mail.smtp.host", smtpHostServer);
props.put("mail.smtp.starttls.enable", "true");
Session session = Session.getInstance(props, null);
EmailUtil.sendEmail(session, emailID,"SimpleEmail Testing Subject", "SimpleEmail Testing Body");
}
}
EmailUtil class:
public class EmailUtil {
/**
* Utility method to send simple HTML email
* #param session
* #param toEmail
* #param subject
* #param body
*/
public static void sendEmail(Session session, String toEmail, String subject, String body){
try
{
MimeMessage msg = new MimeMessage(session);
//set message headers
msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
msg.addHeader("format", "flowed");
msg.addHeader("Content-Transfer-Encoding", "8bit");
msg.setFrom(new InternetAddress("no_reply#example.com", "NoReply-JD"));
msg.setReplyTo(InternetAddress.parse("no_reply#example.com", false));
msg.setSubject(subject, "UTF-8");
msg.setText(body, "UTF-8");
msg.setSentDate(new Date());
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail, false));
System.out.println("Message is ready");
Transport.send(msg);
System.out.println("EMail Sent Successfully!!");
}
catch (Exception e) {
e.printStackTrace();
}
}
}
With this implementation, it is said I do not need any password at all so i gave this a tried and it tells me:
com.sun.mail.smtp.SMTPSendFailedException: 530-5.5.1 Authentication Required
I got this code from an online resources and from what I read,it should be able to send without authentication.
So my question is, do I always need to set a username and password to send mail using JAVA mail?
If no, what am I doing wrong?
It depends on who's running the server.
See https://support.google.com/a/answer/176600?hl=en&vid=0-974788924023-1554173451081; specifically the column labeled 'Gmail SMTP server' (which you're using). Google explicitly says that you have to authenticate to utilize that server. Not doing so gives you this error message.
Once upon a time you could use any mail server to send emails to any email address you wanted.
And then came SPAM. Spammers also could use any mail server to send emails to any email address - and as a mail server operator you do not want spammers to use your server for sending emails (because operating the server costs you money, because your mail server can get blacklisted for spamming).
So today most mail servers require that you
either provide authentication (for sending emails to any email address you want)
or are only allowed to send emails to email addresses hosted by the mail server operator
Google even has two distinct mail servers:
one that requires authentication, that can be used for sending emails to any email address you want (that is the server at smtp.gmail.com)
one that doesn't require authentication, that can only be used for sending emails to Gmail or G Suite users (that is the server aspmx.l.google.com)
It could be that your source dates back to a time when no authentication was required or that the mail server in your source was only used for sending mails to addresses that are hosted at the mail server.
Either way - if you want to use the server smtp.gmail.com for sending mails to any address you must authenticate (or convince google that they should allow you - and only you - to sending emails without authentication, but then: how will google know that it is exactly you who is trying to send mails?)

Using Gmail aliases to link mail replies to application content

I have the following use case in my app:
When a specific event happens in the app all interested users should be notified by email. Then if a user replies to the email, his reply should be shown in the event page in the app.
My initial idea was to create a temp mail alias of the main notification email every time when an event happens and send the notification email with that alias set in the Reply-To header. Then if someone replies to that mail by using the alias (let's say csa123423#mydomain.com) I can figure out which event this reply refers to.
It turned out that Spring's JavaMailSender doesn't provide a way to use aliases, so I tried with Gmail API. As far as I understood creating a Gmail alias means actually setting an already existing email in your domain as an alias for another already existing email in that domain. So the Java code to achieve this using Directory API and Gmail API would look like this:
User newUser = new User();
UserName userName = new UserName();
userName.setGivenName("xsd");
userName.setFamilyName("ewrewr");
newUser.setPrimaryEmail("bbb34262bb45#mydomain.com");
newUser.setPassword("12345");
newUser.setName(userName);
User result = directoryService.users().insert(newUser).execute();
SendAs sendAs = new SendAs().setSendAsEmail("bbb34262bb45#mydomain.com").setReplyToAddress("bbb34262bb45#mydomain.com").setDisplayName("My name").setTreatAsAlias(true);
SendAs sendAsResult = gmailService.users().settings().sendAs().create(user, sendAs).execute();
MimeMessage emailContent = createEmail("mymail#gmail.com", "bbb34262bb45#mydomain.com", "Test from app", "Test body");
Message message = createMessageWithEmail(emailContent);
message = gmailService.users().messages().send(user, message).execute();
But as far as I know there are some limits on the number of accounts you can create per domain/account and also Google would charge more for this.
Is there another easier way to create aliases in Gmail? Or is there another approach to achieve the desired functionality (linking mail replies to application content) without using mail aliases?
Try leveraging '+' functionality given by Gmail for creating temporary aliases.
The basic idea is if my email id is xyz#gmail.com, I can send/receive an email with xyz+1#gmail.com or xyz+anything_here#gmail.com and it will work like a charm.
You can utilize this by keeping the alias/unique-id after the '+' in the Gmail id and then parse this alias easily in your application.

How to get an SMTP response using Javamail

I'm using Javamail to connect to an AWS email service; I've tested that I can receive emails using this code, but I would also like to get a response with data about the sent email, such as the Message ID, which AWS uses to uniquely identify a message.
I'm using MimeMessage to create an email and I am sending it with this code within a try catch block:
transport.sendMessage(message, message.getAllRecipients)
This code just fires off an email to the AWS server and I can't get any metadata back. Is there a way to listen for a response to see if the message was successful so I can retrieve the Message ID?
If the sendMessage method returns, the server accepted the message. Note that that doesn't necessarily mean it will be delivered to the recipient, however. But at that point you can use the getMessageID method to retrieve the message ID.
If the send method throws an exception, the server refused to accept the message for some reason and it won't be sent.
add properties mail.smtp.reportsuccess and mail.smtp.sendpartial to you java Mail Properties, you will get SMTPAddressSucceededException if send email success or SMTPAddressFailedException in fail.
javamail doc

Send Email from one address server to another server using Java Mail API

I have an online form that allows users to email a complaint to the company. To test it I have used gmail smtp as my host. I have no problem receiving the message to the designated email account when the sender is also a gmail but I want the "From" to not be limited to just gmail accounts. It appears that smtp is only good for sending emails from the same server?
Example: My form works great if the from is abc#gmail.com and the company email is company#gmail.com.
However if xyz#yahoo.com is entered for the sender, the receiver company#gmail.com never gets it.
Any help would be greatly appreciated. I can provide my code as well if that is needed.
Your problem is a common security restriction when using SMTP. Outgoing SMTP email can only contain a "mail from" address belonging to the sender. If you break this rule, your email may be considered SPAM.
The following will allow your recipient to reply to an alternate address.
Properties properties = new Properties();
props.put("mail.smtp.from", "abc#gmail.com");
Session session = Session.getDefaultInstance(props, null);
MimeMessage m = new MimeMessage(session);
m.addFrom(InternetAddress.parse("xyz#yahoo.com"));
m.setReplyTo(InternetAddress.parse("xyz#yahoo.com"));
See also
http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/
http://www.openspf.org/Best_Practices/Webgenerated
Well you will have to own the other email as well as set it to work with gmail,
Check here for more details.
It's probably better to send the message to your company's mail server using the identity of the user who owns the application on the server, and include the information that the customer provides in the online form as data in the message you send. The message won't look like it came from the customer, but then it really didn't come from the customer since it wasn't sent using the customer's mail server.

Categories

Resources