This is my class that holds methods for sending email. I am using JavaMail API to send email. I checked multiple times if I pass right arguments from EmailAccount (<- it is a class that I created) and it seems correct. The problem is that I do not get any error or warning, all that is happening is that when program reaches Transport.send(msg); nothing is happening. It does not freeze or crash it is just running (it is like Transport.send(msg) is never completed). To close the program I have to break it manually from IDE. I will glad for any solutions to my problem.
public class EmailTools
{
public void sendEmail(EmailAccount emailAccount, String addressOfReceiver, String title, String text)
{
Properties props = new Properties();
props.put("mail.smtp.host", emailAccount.getSmtpHost());
props.put("mail.smtp.socketFactory.port", Integer.toString(emailAccount.getSslPort()));
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSlSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", Integer.toString(emailAccount.getSmtpPort()));
props.put("mail.host", emailAccount.getSmtpHost());
//Creating Authenticator
javax.mail.Authenticator auth = new javax.mail.Authenticator()
{
#Override
protected javax.mail.PasswordAuthentication getPasswordAuthentication()
{
return new javax.mail.PasswordAuthentication(emailAccount.getEmailAddress(), emailAccount.getPassword());
}
};
//Starting session
Session session = Session.getDefaultInstance(props, auth);
createAndSendEmail(session, emailAccount, addressOfReceiver, title, text);
}
public void createAndSendEmail(Session session, EmailAccount emailAccount, String receiver, String title, String message)
{
try
{
MimeMessage msg = new MimeMessage(session);
//Header stuff
msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
msg.addHeader("format", "flowed");
msg.addHeader("Content-Transfer-Encoding", "8bit");
msg.setFrom(new InternetAddress(emailAccount.getEmailAddress(), "NoReply-JD"));
msg.setSubject(title, "UTF-8");
msg.setText(message, "UTF-8");
msg.setSentDate(new Date());
msg.setReplyTo(InternetAddress.parse(emailAccount.getEmailAddress(), false));
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(receiver, false));
Transport transport = session.getTransport("smtps");
//EDIT1 transport.connect(emailAccount.getSmtpHost(),emailAccount.getSmtpPort(),emailAccount.getEmailAddress(),emailAccount.getPassword());
transport.sendMessage(msg,msg.getAllRecipients());
transport.close();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
public static void main(String args[])
{
EmailAccount emailAccount = new EmailAccount("example#gmail.com","smtp.gmail.com","password","",465,465);
EmailTools emailTools = new EmailTools();
emailTools.sendEmail(emailAccount,"example#gmail.com","Title","Text");
}
}
EDIT1:
I managed to solve the problem and got connected. But now i got the exception
javax.mail.AuthenticationFailedException: 534-5.7.14 <https://accounts.google.com/ContinueSignIn?sarp=1&scc=1&plt=AKgnsbuuA
534-5.7.14 2SN9pvdVb-g3yxJj_u5P7eeAJOoLRRJMVevSThdvunt1c2qCcjkt9FRerrmg9YkB3UDbkc
534-5.7.14 wQDcDG8k4c8GcLrteODlY_danNGhcrg_bxE2_SgYioZK4nH0SzNW1K6-ZRCSlm-mTb6Auj
534-5.7.14 UOr5UqyodVDPHCi8fAmsRF-s30sF29nAdzNMjchSccoo3gwHYixRKSTb69XYWpat1SgRHK
534-5.7.14 FIJ5GjQ> Please log in via your web browser and then try again.
534-5.7.14 Learn more at
534 5.7.14 https://support.google.com/mail/bin/answer.py?answer=78754 ll20sm5684460wic.14 - gsmtp
EDIT2:
Problem solved. It helped me a lot with gmail problem:
Unable to send email via google smtp on centos VPS
Related
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
i want to use javamail so i test this code
public class Test_Mail {
public static void main(String [] args)
{
String to="xyz#gmail.com";//change accordingly
//Get the session object
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("abc#gmail.com","*****");
}
});
//compose message
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("abc#gmail.com"));//change accordingly
message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
message.setSubject("Hello");
message.setText("Testing.......");
//send message
Transport.send(message);
System.out.println("message sent successfully");
} catch (MessagingException e) {throw new RuntimeException(e);}
}
}
but i have this error:
Exception in thread "main" java.lang.RuntimeException: javax.mail.AuthenticationFailedException: 534-5.7.14 Please log in via your web browser and
534-5.7.14 then try again.
534-5.7.14 Learn more at
534 5.7.14 https://support.google.com/mail/bin/answer.py?answer=78754 gj16sm129363wic.24 - gsmtp
i tried many changes but it's the same error.
Because Google is such a large target for SPAM they have policies and practices in place to try and prevent as much SPAM as possible. It appears that your account may have been flagged by one of these policies and requires some manual intervention to get it working again.
I have a MailSender class that has 2 methods:
private Session createSmtpSession(final String fromEmail, final String fromEmailPassword) {
final Properties props = new Properties();
props.setProperty ("mail.host", "smtp.gmail.com");
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.smtp.port", "" + 587);
props.setProperty("mail.smtp.starttls.enable", "true");
props.setProperty ("mail.transport.protocol", "smtp");
return Session.getDefaultInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(fromEmail, fromEmailPassword);
}
});
}
public void sendEmail(String subject, String fromEmail, String fromEmailPassword, String content, String toEmail){
Session mailSession = createSmtpSession(fromEmail, fromEmailPassword);
mailSession.setDebug (true);
try {
Transport transport = mailSession.getTransport ();
MimeMessage message = new MimeMessage (mailSession);
message.setSubject (subject);
message.setFrom (new InternetAddress (fromEmail));
message.setContent (content, "text/html");
message.addRecipient (Message.RecipientType.TO, new InternetAddress (toEmail));
transport.connect ();
transport.sendMessage (message, message.getRecipients (Message.RecipientType.TO));
}
catch (MessagingException e) {
System.err.println("Cannot Send email");
e.printStackTrace();
}
}
ok, The way the above code works is like this:
I have personal gmail myEmail#gmail.com & if I want to send msg to destination email like aa#xyz.com from myEmail#gmail.com, then I need to call sendEmail(subject, "myEmail#gmail.com", fromEmailPassword, content, "aa#xyz.com");
But recently I bought VPS from Godaddy & I am using Godaddy Email (info#mydomain.com) so I want to send smg to destination email like aa#xyz.com from info#mydomain.com, then I need to call sendEmail(subject, "info#mydomain.com", fromEmailPassword, content, "aa#xyz.com");
However I got error cos Godaddy using port 25
So I changed the code in createSmtpSession as following:
props.setProperty ("mail.host", "smtp.mydomain.com");
props.setProperty("mail.smtp.port", "" + 25);
However, this time I got other problem
DEBUG SMTP: Sending failed because of invalid destination addresses
RSET
250 2.0.0 OK
DEBUG SMTP: MessagingException while sending, THROW:
javax.mail.SendFailedException: Invalid Addresses;
nested exception is:
com.sun.mail.smtp.SMTPAddressFailedException: 550 5.1.1 <aa#xyz.com> Recipient not found. <http://x.co/irbounce>
Clearly the aa#xyz.com is actually existed, but why the error saying Recipient not found.
SO How to fix this issue?
I need to look at the outgoing (SMTP) server (like smtpout.secureserver.net) in Godaddy Email & now it working fine
props.setProperty ("mail.transport.protocol", "smtps");
props.setProperty ("mail.smtps.host", "smtpout.secureserver.net");
props.setProperty("mail.smtps.auth", "true");
props.setProperty("mail.smtps.port", "" + 465);
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
I have a program where I have a number of users which each could be sending emails from different email accounts.
When I try to use JavaMail to send emails. They always get sent out by the account of the user who sent an email first.
user1 = new User("dummy-email#gmail.com", "dumpass12");
user2 = new User("second-dummy#gmail.com", "secondpass12");
user1.sendMail(toAddress, subject, body);
user2.sendMail(toAddress, subject, body);
Now when I do something like this, the second user will send a message but it will come from the SAME mailbox as user1 (i.e. both messages will come from dummy-email#gmail.com).
Can somebody explain to me why this is happening? Do I have to close the connection somehow? How can I send the two emails and have them come from the different accounts? Please help me.
Here is my code which actually sends the email connecting to the user's gmail account.
public void sendMail(String toAddress, String subject, String body){
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator()
{
protected PasswordAuthentication getPasswordAuthentication()
{ return new PasswordAuthentication(getUsername(),getPassword()); }
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(getUsername()));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(toAddress));
message.setSubject(subject);
message.setContent(body, "text/html");
Transport.send(message);
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
Replace Session.getDefaultInstance() with Session.getInstance(). To understand why, read the javadocs for those methods carefully.