Cannot send email without authentication required - java

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?)

Related

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

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

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.

Java to *get* mail from SMTP sevrer

I'm trying to get an email from exchange SMTP server (port 25).
all the examples i saw are to send an email with SMTP while i would like to get (read) an email.
I wrote a code using JAVAMail that get email with impas that work perfect but in the last mooment the demand change to use SMTP for incoming mail.
Java code for IMAP incoming mail
public void getAttachment() throws MessagingException, IOException {
properties.setProperty("exchange server host",host);
properties.put("smtp.gmail.auth", "true");
Session session = Session.getDefaultInstance(properties, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
}
);
Store store = session.getStore("imaps");
try {
logger.info(String.format("Going to get connection to exchange server %s for user %s " ,host, user));
store.connect(host, user, password);
}
catch (MessagingException ex){
logger.error(String.format("Unable to connect exchange server {}", host) + ex.getMessage());
logger.error(ex.getStackTrace());
}
Folder inboxFolder = store.getFolder("inbox");
inboxFolder.open(Folder.READ_WRITE);
// search for all "unseen" messages
Flags seen = new Flags(Flags.Flag.SEEN);
FlagTerm unseenFlagTerm = new FlagTerm(seen, false);
Message[] message = inboxFolder.search(unseenFlagTerm);
Can someone please advise for getting mail with SMTP protocol and not with IMAP?
can it be done ?
Thanks.
You can't.
SMTP is for a client to send email to a server.
In order for a client to receive email from a server, you need to use protocols like POP3 (Post Office Protocol) or IMAP (Internet Message Access Protocol).
Actually, the Wikipedia page for SMTP says as much:
User-level email clients typically use SMTP only for sending messages to a mail server for relaying, typically submit outgoing email to the mail server on port 587 or 465 as per RFC 8314. For retrieving messages, IMAP and POP3 are standard, but proprietary servers also often implement proprietary protocols, e.g., Exchange ActiveSync.

Cannot send email using Java code on Windows Server 2008 r2?

I have installed SMTP server and IIS Web server on windows 2008 r2 server. I am trying to send a test email using java code through localhost but i am unable to send an email i get the following error not sure what is that i am doing wrong. Apart from installing the SMTP server is there any setting i need to do because i just installed my smtp server and expecting that this code works?
javax.mail.SendFailedException: Invalid Addresses;
nested exception is:
com.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1 Unable to relay for marshell#gmail.com
at com.sun.mail.smtp.SMTPTransport.rcptTo(SMTPTransport.java:1862)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1118)
at javax.mail.Transport.send0(Transport.java:195)
at javax.mail.Transport.send(Transport.java:124)
at LotusNotes.SendEmail.main(SendEmail.java:30)
Caused by: com.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1 Unable to relay for marshell#gmail.com at com.sun.mail.smtp.SMTPTransport.rcptTo(SMTPTransport.java:1715)
Java Code:
public static void main(String[] args) {
String to = "marshell#gmail.com";
String from = "imrmsmtpmail";
String host = "localhost";
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
Session session = Session.getDefaultInstance(properties);
try{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("Subject Line!");
message.setText("Test email!");
Transport.send(message);
System.out.println("Sent message successfully....");
}
catch (MessagingException mex) {
mex.printStackTrace();
}
}
Probably you have to authenticate to send emails to this server.
AFAIK, you aren't providing any user or password in the connection to the server.
I use something like this:
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.smtp.auth", true);
properties.setProperty("mail.user", "PUT AN USERNAME HERE");
properties.setProperty("mail.password", "PUT A PASSWORD HERE");
Session session = Session.getDefaultInstance(properties);
And to make sure you have all the parameters working properly before writing the program it is useful to make a telnet to the mail port (25) to make sure you can send an email directly writing the codes into the server.
In the following link you have an example:
http://support.microsoft.com/kb/153119/en
Altough it may sound extremely technical, it worth to try to make sure that the server send emails from your machine with the given parameters: username (or not username at all), destination address, etc.

Sending a mail to any message server (Gmail, Yahoo etc) without password authentication in Java

We are developing a simple web application in JSF in which there is a need to include a "forget password" module. For the sake of demonstration and simplicity, I tried the following code in Java Servlet. It can send a mail to Gmail and works just fine there is no problem at all. The following is the complete Servlet code.
public class MailClient extends HttpServlet {
private class SMTPAuthenticator extends Authenticator {
private PasswordAuthentication authentication;
public SMTPAuthenticator(String login, String password) {
authentication = new PasswordAuthentication(login, password);
}
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return authentication;
}
}
protected void processRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
String from = "bhaveshp1980#gmail.com";
String to = "bhaveshp1980#gmail.com";
String subject = "A mail from Java.";
String message = "My first mail from Java.";
String login = "bhaveshp1980#gmail.com";
String password = "password";
Properties props = new Properties();
props.setProperty("mail.host", "smtp.gmail.com");
props.setProperty("mail.smtp.port", "587");
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.smtp.starttls.enable", "true");
Authenticator auth = new SMTPAuthenticator(login, password);
Session session = Session.getInstance(props, auth);
MimeMessage msg = new MimeMessage(session);
try {
msg.setText(message);
msg.setSubject(subject);
msg.setFrom(new InternetAddress(from));
msg.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
Transport.send(msg);
} catch (MessagingException ex) {
Logger.getLogger(MailClient.class.getName()).
log(Level.SEVERE, null, ex);
}
} finally {
out.close();
}
}
#Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
#Override
public String getServletInfo() {
return "Short description";
}
}
Now, the first question is that as soon as a user enters his valid email address, a verification code should be submitted to a specific message server (Gmail, Yahoo and so on) without asking the user for his password (Which is not the case of the above code) which is essential in implementing the "forget password" module in a web application.
The second question is that the above code is bound to sending a mail only to Gmail. If I want to send a mail to some other message server say Yahoo, the statement
props.setProperty("mail.host", "smtp.gmail.com");
needs to be changed to
props.setProperty("mail.host", "smtp.mail.yahoo.com");
[and port no too, regarding others] means that a specific message server to which a message has to be sent need to be recognized properly. Which is the best way to do so?. What is the best method(s) to overcome these issues, please.
Do you change your SMTP settings in your email client each time you send a mail to a different mail provider? No. You don't set the SMTP server to gmail when sending a mail to a gmail.com address. And then set it to yahoo when sending a mail to a yahoo.com address. You set it to your email provider SMTP server, and this SMTP server sends the mail to the appropriate location.
Just choose an SMTP server which agrees to send mails from your application. Sending a dozen per day will be OK with any SMTP provider. But if you send thousands a day, then you could have problems with your provider. Just ask your hosting provider how it goes with outgoing mails (how much it costs, how many per day are accepted, is there a bandwidth limit, etc.)
So you can't do that. That's the whole point of keeping people from spamming, masquerading as users they aren't, and lots of other nasty things.
You need to setup a SMTP server or get your domain hosted on a mail service that you can send mail through. Maybe your ISP or hosting provider provides this already and you just need to sign up for that. Otherwise, there are plenty of places out there that will allow you to send mail from your domain. I use:
http://www.authsmtp.com/
Or you can have google host your domain for free, but they put a limit on the number of messages you can send per day which last time I checked was like 100. So if your site plans on sending more mail than that you need to bump up to paid service like authsmtp.
http://www.google.com/apps/intl/en/business/smb/email.html#utm_campaign=en&utm_source=en-ha-na-us-sk&utm_medium=ha&utm_term=%2Bemail%20%2Bhosting
Basically you need to find a mail server that is in charge of your MX record so emails sent to your domain will get routed to those servers, and so you application can send email from your domain and not get black listed as a spammer because you are doing naughty things.
While you can setup your own smtp server it's just so much easier to use a service, and that gives you a professional look for doing things like customer service, and responding to people when you mail comes from a domain associated with your website and not some johnnyappleseed#gmail.com
You need to do some basic research about how email works from a technical perspective as well. That will help you understand why what I'm talking about is important.
The authentication part you cannot get around. This is configured in the remote server, so unless you use your own mailserver, you have to do what gmail asks you to do. But instead of hardcoding the login/password, you could store them in an (encrypted?) properties file and modify that whenever you want to use another mailserver.
You need to generate a random token and send it as part of the
message. You store the token in the database with an association to
the user's profile. When the user returns to your site with that
token (by entering it into a form, or by clicking a link with that
token as GET parameter) you can be sure the user is authentic and
offer the reset password dialog.
Don't send the message to the smtp server of the recipient, but to
the smtp server of your from email address. So sending it to gmail
would be fine. I would make stmp host url, username and password
configurable, e.g. in a property file.

Categories

Resources