I am writing an email client to send email using yahoo SMTP server.
Getting error: com.sun.mail.smtp.SMTPSendFailedException: 554 Email rejected
Passed Authentication but throwing 554 while sending email:-
public static void main(String[] args) {
final String fromEmail = "myyahoo#yahoo.com"; //requires valid id
final String password = "xxxxxxx"; // correct password for gmail id
final String toEmail = "test.existing#gmail.com"; // can be any email id
System.out.println("TLSEmail Start");
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.mail.yahoo.com"); //SMTP Host
props.put("mail.smtp.port", "587"); //TLS Port
props.put("mail.smtp.auth", "Required"); //enable authentication
props.put("mail.smtp.starttls.enable", "true"); //enable STARTTLS
//create Authenticator object to pass in Session.getInstance argument
System.out.println("Calling getPasswordAuthentication");
Authenticator auth = new Authenticator() {
//override the getPasswordAuthentication method
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(fromEmail, password);
}
};
System.out.println("After getPasswordAuthentication");
Session session = Session.getInstance(props, auth);
EmailUtil.sendEmail(session, toEmail,"My First TLSEmail Testing Subject", "My first email client. TLSEmail Testing Body");
}
Output:-
TLSEmail Start
Calling getPasswordAuthentication
After getPasswordAuthentication
Message is ready
com.sun.mail.smtp.SMTPSendFailedException: 554 Email rejected
at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:2358)
at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:1823)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1300)
at javax.mail.Transport.send0(Transport.java:255)
at javax.mail.Transport.send(Transport.java:124)
at EmailUtil.sendEmail(EmailUtil.java:48)
at MyEmail.main(MyEmail.java:38)
What is the problem here.
Here is class EmailUtil:
public class EmailUtil {
public static void sendEmail(Session session, String toEmail, String subject, String body){
try
{
MimeMessage msg = new MimeMessage(session);
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();
}
}
}
This client sends email using gmail SMTP server.
If you read here https://serversmtp.com/port-outgoing-mail-server/ and also here https://getmailspring.com/setup/access-yahoo-com-via-imap-smtp
You will notice that yahoo uses port 465 and in your code i see 587
Related
This question already has answers here:
JavaMail API : Username and Password not accepted (Gmail)
(2 answers)
How can I send an email by Java application using GMail, Yahoo, or Hotmail?
(14 answers)
Closed 2 years ago.
I am trying to send email in this code but every time it is showing username and password not accepted.
but I have done everything. I have also set my gmail account to access third party apps. Now I don't understand where is the problem is.
Exception in thread "main" javax.mail.AuthenticationFailedException: 535-5.7.8 Username and Password not accepted. Learn more at
535 5.7.8 https://support.google.com/mail/?p=BadCredentials d8sm6051763pfd.159 - gsmtp
at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:965)
at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:876)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:780)
at javax.mail.Service.connect(Service.java:388)
at javax.mail.Service.connect(Service.java:246)
at javax.mail.Service.connect(Service.java:195)
at javax.mail.Transport.send0(Transport.java:254)
at javax.mail.Transport.send(Transport.java:124)
at com.mirajhossain.TransMail.sendMail(Main.java:37)
at com.mirajhossain.Main.main(Main.java:52)][1]
Here is my code.
class TransMail{
public static void sendMail(String recepient) throws MessagingException {
Properties properties=new Properties();
properties.put("mail.from","REDACTED");
properties.put(" mail.user","REDACTED");
properties.put(" mail.passr","REDACTED");
properties.put("mail.smtp.auth","true");
properties.put("mail.smtp.starttls.enable","true");
properties.put("mail.smtp.host","smtp.gmail.com");
properties.put("mail.smtp.ssl.trust", "smtp.gmail.com");
properties.put("mail.smtp.port","587");
String myAccount="miraj98hossain#gmail.com";
String pwd="69miraj69hossain69shawon69";
Session session= Session.getInstance(properties, new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(myAccount,pwd);
}
});
Message message= preparemessage(session,myAccount,recepient);
Transport.send(message);
System.out.println("yes");
}
private static Message preparemessage(Session session, String myAccount,String recepient) throws MessagingException {
Message message=new MimeMessage(session);
message.setFrom(new InternetAddress(myAccount));
message.setRecipient(Message.RecipientType.TO,new InternetAddress(recepient));
message.setSubject("Verification");
message.setText("1254562");
return message;
}
}
public class Main{
public static void main(String[] args) throws MessagingException {
TransMail.sendMail("miraj09hossain#gmail.com");
}
}
Make sure you have to turn on less secure app access from your gmail account settings.
public class Main {
public static void main(String [] args)
{
// Sender's email ID needs to be mentioned
String from = "test#gmail.com";
String pass ="xxxxxxx";
// Recipient's email ID needs to be mentioned.
String to = "test313#gmail.com";
String host = "smtp.gmail.com";
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.user", from);
properties.put("mail.smtp.password", pass);
properties.put("mail.smtp.port", "587");
properties.put("mail.smtp.auth", "true");
// Get the default Session object.
Session session = Session.getDefaultInstance(properties);
int Vcode=(int)(10000+Math.random()*(20000-10000+1));
try{
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
// Set Subject: header field
message.setSubject("Email Verification");
// Now set the actual message
message.setText("Your verification code for our app is"+Vcode+".\n"+"Enter this code for complete your sign up process");
// Send message
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
I am using JavaMail library. Look how it looks:
Configure:
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setHost(host); // for example smtp.gmail.com
mailSender.setPort(port); // 465
mailSender.setUsername(username); // your email
mailSender.setPassword(password); // your password
Properties properties = mailSender.getJavaMailProperties();
properties.setProperty("mail.transport.protocol", protocol); // smtps
properties.setProperty("mail.debug", debug); // as you wish
properties.setProperty("mail.smtp.auth", auth); // true
properties.setProperty("mail.smtp.starttls.enable", enable); // true
}
Send message:
private void send(String subject, String message) {
SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setFrom(emailFrom);
mailMessage.setTo(emailTo); // receiver
mailMessage.setSubject(subject);
mailMessage.setText(message);
mailSender.send(mailMessage);
}
Try this.
In the following Code in the session object (PasswordAuthentication ) what username and password we have to provide to send mail ? Sender's username password or receiver's credentials?
I am really confused , I am using java Mail to send mail
public void sendMail(String email,String token)
{
// Recipient's email ID needs to be mentioned.
String to = email;
// Sender's email ID needs to be mentioned
// Assuming you are sending email through relay.jangosmtp.net
String host = "smtp.gmail.com";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "587");
// Get the Session object.
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
// Create a default MimeMessage object.
Message message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress("Issme-Customer-Service"));
// Set To: header field of the header.
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
message.setSubject("Email Verification Of issme Account");
message.setContent(
"<h2>Email Verification </h2>" +
"<h3> Please goto the following URL to verify your ISSME account\n </h3> " +
token , "text/html; charset=utf-8");
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
You need to send the sender's credentials which gmail's SMTP server will authenticate and then it'll send the email.
I am trying to send an email using java client api. No matter what I try, I get this json error:
{
"code": 403,
"errors": [
{
"domain": "global",
"message": "Invalid user id specified in request/Delegation denied",
"reason": "forbidden"
}
],
"message": "Invalid user id specified in request/Delegation denied"
}
Any ideas how to bypass this error??
The code relevant to the specific issue, creating a MIME message and then creating the according Message as needed:
#Path("/sendmessage/{to}/{from}/{subject}/{body}/{userID}")
#GET
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response sendMessage(
#PathParam("to")String to,
#PathParam("from") String from,
#PathParam("subject") String subject,
#PathParam("body") String body,
#PathParam("userID") String userID)
{
MimeMessage mimeMessage =null;
Message message = null;
mimeMessage =createEmail(to, from, subject, body);
message = createMessageWithEmail(mimeMessage);
gmail.users().messages().send(userID,message).execute();
resp = Response.status(200).entity(message.toPrettyString()).build();
return resp;
}
public static MimeMessage createEmail(String to, String from, String subject, String bodyText){
Properties props = new Properties();
String host = "smtp.gmail.com";
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", "******");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props);
MimeMessage email = new MimeMessage(session);
try{
InternetAddress toAddress = new InternetAddress(to);
InternetAddress fromAddress = new InternetAddress(from);
email.setFrom(fromAddress);
email.addRecipient(javax.mail.Message.RecipientType.TO, toAddress);
email.setSubject(subject);
email.setText(bodyText);
Transport transport = session.getTransport("smtp");
transport.connect(host, from, ********);
transport.sendMessage(email, email.getAllRecipients());
transport.close();
}
catch(Exception e){
LOGGER.error("Class: "+className+", Method: "+methodName+", "+e.getMessage());
}
return email;
}
public static Message createMessageWithEmail(MimeMessage email){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
email.writeTo(baos);
} catch (IOException | MessagingException e) {
LOGGER.error("Class: "+className+", Method: "+methodName+", "+e.getMessage());
}
String encodedEmail = Base64.encodeBase64URLSafeString(baos.toByteArray());
Message message = new Message();
message.setRaw(encodedEmail);
return message;
}
Pass empty string or "me" as the userId in the Gmail API call:
gmail.users().messages().send("", message).execute();
please try this
public static boolean sendEmail(String subject,String to,String content, MultipartFile file,String filenameName) throws Exception{
try{
final String username = "***#gmail.com";
final String password = "***";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");// For gmail Only U can change as per requirement
props.put("mail.smtp.port", "587"); //Different port for different email provider
props.setProperty("mail.smtp.auth", "true");
Session session = Session.getInstance(props,new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
session.setDebug(true);
Message message = new MimeMessage(session);
message.setHeader("Content-Type","text/plain; charset=\"UTF-8\"");
message.setSentDate(new Date());
message.setFrom(new InternetAddress(username));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
message.setSubject(subject);
if(file!=null){
//-Multipart Message
Multipart multipart = new MimeMultipart();
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(content);
multipart.addBodyPart(messageBodyPart);//Text Part Add
// Part two is attachment
messageBodyPart= new MimeBodyPart() ;
ByteArrayDataSource source=new ByteArrayDataSource(file.getBytes(),"application/octet-stream");
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
//Send the complete message parts
message.setContent(multipart);
}
else
message.setText(content);
//message.setText(content);
Transport.send(message);
}
catch(Exception e){
return false;
}
return true;
}
Generally this type of error occurs when authenticated email address and from email address miss match occurs.
So, if you are using client library then pass "me" or empty string while executing as shown in below
gmail.users().messages().send("me", message).execute();
if you are using rest api then use
https://www.googleapis.com/gmail/v1/users/me/messages
I need to send mail from my gmail account to another. I used the following code.
String fromaddress = "xxx#gmail.com";
String password = "yyy";
String hostname = "smtp.gmail.com";
String hoststring = "mail.smtp.host";
String toaddress = "yyy#gmail.com";
String emailcontent;
Properties properties = System.getProperties();
properties.setProperty(hoststring, hostname);
Session session = Session.getDefaultInstance(properties);
try{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(fromaddress));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(toaddress));
message.setSubject("hi");
emailcontent = "hi...";
message.setText(emailcontent);
System.out.println(emailcontent);
Transport.send(message);
System.out.println("Sent....");
}catch (MessagingException mex)
{
mex.printStackTrace();
}
But i get the error as follows...
javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 25
How am i to solve this. Can you please help me out.
public static void sendEmail(Email mail) {
String host = "smtp.gmail.com";
String from = "YOUR_GMAIL_ID";
String pass = "YOUR_GMAIL_PASSWORD";
Properties props = System.getProperties();
props.put("mail.smtp.starttls.enable", "true"); // added this line
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", pass);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
// Get the default Session object.
Session session = Session.getDefaultInstance(props, null);
try {
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set sender
message.setFrom(new InternetAddress("Senders_EMail_Id"));
// Set recipient
message.addRecipient(Message.RecipientType.TO, new InternetAddress("RECIPIENT_EMAIL_ID"));
// Set Subject: header field
message.setSubject("SUBJECT");
// set content and define type
message.setContent("CONTENT", "text/html; charset=utf-8");
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
} catch (MessagingException mex) {
System.out.println(mex.getLocalizedMessage());
}
}
}`
I think this should do the trick.
I think you need to change the port no. 25 to 587
you can get help from
http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/
gmail setting help link:
http://gmailsmtpsettings.com/
Just adding few more tweaks to the question above:
Change the port to 465 to enable ssl sending.
I don't think above code will work, as you need to have an authenticator object too. As smtp also requires authentication in case of gmail.
You can do something like:
Have a boolean flag,
boolean authEnable = true; //True for gmail
boolean useSSL = true; //For gmail
//Getters and setters for the same
if (isUseSSL()) {
properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
properties.put("mail.smtp.socketFactory.port", "465");
}
Authenticator authenticator = new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("abc#gmail.com", "xyz"));
}
};
if (isAuthEnable()) {
properties.put("mail.smtp.auth", "true");
session = Session.getDefaultInstance(properties, authenticator);
} else {
session = Session.getDefaultInstance(properties);
}
I am trying out an email app on android.I take the username and password first
then on the next activity i take the recipiend address subject and msg and send the email.
I get the error JavaX authentication failure.Here is my Mail authentication and sending code.OnClick function of the send button calls this class
public class MailHandler {
final String username;
final String password;
public MailHandler(String username,String password){
this.username=username;
this.password=password;
}
public void sendMail(String Sub,String msg,String sender,String cc,String to) {
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(sender));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
message.setSubject(Sub);
message.setText(msg);
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
A simple solution is to use the final String parameters, such as
public void sendMail(final String username ,final String password );.
Your code works. I copied it compiled and ran it using my gmail credentials. Are you sure you are using the correct gmail credentials for sending mail?
MailHandler m = new MailHandler("myAccount#gmail.com", "myPassword");
m.sendMail("Test", "Testing", "myOtherAccount#gmail.com", "myWork#myCompany.com", "myOtherWork#myCompany.com");
// After running I checked my work email and saw the message.
If I use an invalid password I get the following statcktrace. Is this what you are seeing
535 5.7.1 http://support.google.com/mail/bin/answer.py?answer=14257 jl8sm4152932obb.18
at MailHandler.sendMail(MailHandler.java:50)
at MailHandler.main(MailHandler.java:56)
Caused by: javax.mail.AuthenticationFailedException: 535-5.7.1 Username and Password not accepted. Learn more at
535 5.7.1 http://support.google.com/mail/bin/answer.py?answer=14257 jl8sm4151848obb.18
at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:823)
at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:756)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:673)
at javax.mail.Service.connect(Service.java:317)
at javax.mail.Service.connect(Service.java:176)
at javax.mail.Service.connect(Service.java:125)
at javax.mail.Transport.send0(Transport.java:194)
at javax.mail.Transport.send(Transport.java:124)
at MailHandler.sendMail(MailHandler.java:45)
... 1 more