I am attempting to send an email using Java. From reading, I have found that if I use gmail as the host I can do this for free & it should work, is that correct.
So I have my code below, & I am attempting to send an email from myself to my friends emails(the emails in my code below have been altered for privacy) but I get an exception thrown when I go to send/transfer the email (at the line Transport.send(msg);)
The output/exception thrown is:
javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 25;
nested exception is:
java.net.ConnectException: Connection timed out: connect
Should have succeeded: false
What do you think I am doing wrong?
/**
* SimpleAuthenticator is used to do simple authentication
* when the SMTP server requires it.
*/
class SMTPAuthenticator extends javax.mail.Authenticator
{
public PasswordAuthentication getPasswordAuthentication()
{
String username = "myaccount#gmail.com";
String password = "xxxxxxx";
return new PasswordAuthentication(username, password);
}
}
public class SendEmail
{
public SendEmail()
{
}
public static boolean sendEmail( String from, String to[], String subject, String body )
{
try
{
boolean debug = false;
// Set the host smtp address
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com" ); // "smtp.jcom.net");
props.put("mail.smtp.auth", "true");
// create some properties and get the default Session
// Session session = Session.getDefaultInstance(props, null);
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getDefaultInstance(props, auth);
session.setDebug(debug);
// create a message
Message msg = new MimeMessage(session);
// set the from and to address
InternetAddress addressFrom = new InternetAddress(from);
msg.setFrom(addressFrom);
InternetAddress[] addressTo = new InternetAddress[to.length];
for (int i = 0; i < to.length; i++)
{
addressTo[i] = new InternetAddress(to[i]);
}
msg.setRecipients(Message.RecipientType.TO, addressTo);
// Optional : You can also set your custom headers in the Email if
// you Want
msg.addHeader("MyHeaderName", "myHeaderValue");
// Setting the Subject and Content Type
msg.setSubject(subject);
msg.setContent(body, "text/plain");
System.out.println( "1" );
Transport.send(msg);
System.out.println( "2" );
}
catch (Exception e)
{
System.out.println( e );
return false;
}
return true;
}
public static void main(String args[])
{
boolean res = SendEmail.sendEmail( "myaccount#gmail.com", new String[] {"x#y.com", "y#x.com.au"},
"Test", "Did it work?" );
System.out.println( "Should have succeeded: " + res );
}
}
Google is your friend. Check this site: http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/
Gmail only accepts secure connections using TLS, but you're using the standard non-secure authentication.
Try with the port 465 (found here)
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 am creating a simple java mail program,the program is working ok and the last system print also working .but the problem is i dint received the mail in outlook.here i am using the company outlook.please some one help me.
i am attaching my code here
enter code here
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SimpleSendEmail
{
public static void main(String[] args)
{
String host = "compny host";
String from = "mail id";
String to = "usr#some.com";
String subject = "birthday mail";
String messageText = "I am sending a message using the"
+ " simple.\n" + "happy birthday.";
boolean sessionDebug = false;
Properties props = System.getProperties();
props.put("compny host", host);
props.put("mail.smtp.port", "25");
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.starttls.enable", "true");
Session session = Session.getDefaultInstance(props, null);
// Set debug on the Session so we can see what is going on
// Passing false will not echo debug info, and passing true
// will.
session.setDebug(sessionDebug);
try
{
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = { new InternetAddress(to) };
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setText(messageText);
Transport.send(msg);
System.out.println("Sent message successfully....");
}
catch (MessagingException mex)
{
mex.printStackTrace();
}
}
}
output
Sent message successfully....
"Compny host" doesn't seem like correct host. Check out this tutorial http://www.tutorialspoint.com/java/java_sending_email.htm and here you have also a few examples of sending emails in Java Send email using java
I do expect that you are using the correct host on your side.
But you are missing Username and Password.
transport = session.getTransport("smtp");
transport.connect(hostName, port, user, password);
transport.sendMessage(message, message.getAllRecipients());
or you can use the Authenticator:
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
I want to send email using javax.mail. When I run the following code it give me this error No provider for hwangheera4hagarmaher. Where is the problem, and how can I fix this error ?
the code i used is this:
public static boolean SendMail (String subject, String from, String Password, String Message, String to[])
{
String Host = "hwangheera4hagarmaher#gmail.com";
Properties Property = System.getProperties();
Property.put("mail.hwangheera4hagarmaher.starttls.enable", true);
Property.put ("mail.hwangheera4hagarmaher.host", Host);
Property.put ("mail.hwangheera4hagarmaher.user", from);
Property.put ("mail.hwangheera4hagarmaher.password", Password);
Property.put ("mail.hwangheera4hagarmaher.port", 587);
Property.put ("mail.hwangheera4hagarmaher.auth", "true");
Session session = Session.getDefaultInstance(Property, null);
MimeMessage message = new MimeMessage (session);
try
{
message.setFrom(new InternetAddress (from));
InternetAddress [] toAddress = new InternetAddress[to.length];
for (int i = 0; i < to.length; i++)
{
toAddress [i] = new InternetAddress (to[i]);
}
for (int i = 0; i < toAddress.length; i++)
{
message.addRecipient(RecipientType.TO, toAddress[i]);
}
message.setSubject (subject);
message.setText(Message);
Transport transport = session.getTransport("hwangheera4hagarmaher");
transport.connect (Host, from, Password);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
return true;
}
catch (MessagingException ex)
{
showMessageDialog (null, ex);
}
return false;
}
Replace hwangheera4hagarmaher with smtp in all props and getTransport () unless you have coded a provider by that name yourself.
Your hostname should be a server, not an email address. Maybe smtp.gmail.com?
By default Google provides security precaution for using any external access, especially If you use some email frameworks to access your account , first you need to give access, sign in your account then go to :
https://accounts.google.com/DisplayUnlockCaptcha
Then follow the rest to allow access to your account.
I'm trying to send a mail using SendGrid by deploying my code to GAE. Following is my code.
private static final String SMTP_HOST_NAME = "smtp.sendgrid.net";
private static final String SMTP_AUTH_USER = "*******";
private static final String SMTP_AUTH_PWD = "*******";
private static final int SMTP_PORT = 2525;
public void sendCustomer(String userName, String toEmail, int custId) {
try {
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", "true");
Authenticator auth = new SMTPAuthenticator();
Session mailSession = Session.getDefaultInstance(props, auth);
Transport transport = mailSession.getTransport();
MimeMessage message = new MimeMessage(mailSession);
Multipart multipart = new MimeMultipart("alternative");
// Sets up the contents of the email message
BodyPart part1 = new MimeBodyPart();
part1.setText("Hello "
+ userName
+ "\n\n\n\n"
+ "Welcome to NotionViz. You have been registered successfully in NotionViz.");
multipart.addBodyPart(part1);
message.setText("UTF-8", "html");
message.setContent(multipart);
message.setFrom(new InternetAddress(SMTP_AUTH_USER));
message.setSubject("Customer Registration");
InternetAddress internetAddress = null;
try {
internetAddress = new InternetAddress(toEmail);
internetAddress.validate();
} catch (Exception e) {
System.out.println("Not a valid email address");
}
message.addRecipient(Message.RecipientType.TO, internetAddress);
InternetAddress address = new InternetAddress("cloud.spaninfotech#gmail.com");
message.setFrom(address);
// Sends the email
transport.connect(SMTP_HOST_NAME, SMTP_PORT, SMTP_AUTH_USER,
SMTP_AUTH_PWD);
transport.sendMessage(message,
message.getRecipients(Message.RecipientType.TO));
transport.sendMessage(message,
message.getFrom());
transport.close();
} catch (Exception e) {
}
}
// Authenticates to SendGrid
class SMTPAuthenticator extends javax.mail.Authenticator {
#Override
public PasswordAuthentication getPasswordAuthentication() {
String username = SMTP_AUTH_USER;
String password = SMTP_AUTH_PWD;
return new PasswordAuthentication(username, password);
}
}
This program is working fine and sending mail in local. But if i deploy to GAE and check, I'm not getting an email. Please let me know why GAE restricting third party mail sending.
Try changing the port that you're using. You can hit SendGrid over port 587, 25 or 2525 for plain/TLS connections (465 if you were going to be using SSL).
SendGrid suggests port 587 to avoid rate limits set by some hosting companies so I would give that a shot.
On GAE sockets are a subject to a series of restrictions (see Sockets API documentation). Authenticated SMTP is allowed on submission port 587, so you can use it as already suggested by LaCroixed.
I am new in Java Mail API, I had tried to implement a web application using Tomcat Server which reads I reads gmail inbox and working fine. But when I upload my code to development server it throws below exception
javax.mail.AuthenticationFailedException: [ALERT] Please log in via your web browser: http://support.google.com/mail/accounts/bin/answer.py?answer=78754 (Failure)
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:660)
at javax.mail.Service.connect(Service.java:317)
at sales_order.ReadInquiryViaEmail.run(ReadInquiryViaEmail.java:89)
at java.lang.Thread.run(Thread.java:662)
And my code is
public class ReadInquiryViaEmail implements Runnable {
public ReadInquiryViaEmail(ServletContext context, String emailAddress,
String domainName, String protocol, String password) {
this.sContext = context;
this.domainName = domainName;
this.emailAddress = emailAddress;
this.password = password;
this.protocol = protocol;
}
public void run() {
Properties imapProps;=new Properties();
imapProps.setProperty("mail.host", domainName);
imapProps.setProperty("mail.port", "993");
imapProps.setProperty("mail.transport.protocol", protocol);
imapProps.setProperty("mail.imaps.starttls.enable", "true");
imapProps.setProperty("username", emailAddress);
imapProps.setProperty("password", password);
int port = Integer.parseInt("993");
Authenticator authenticator = new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(emailAddress, password);
}
};
Session mailSession = Session.getInstance(imapProps, authenticator);
try {
Store store = mailSession.getStore(protocol);
store.connect(domainName, port, emailAddress, password);
Folder folder = store.getFolder("Inbox");
folder.open(Folder.READ_WRITE);
folder.getMessages();
FlagTerm term = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
Message[] messages = folder.search(term);
System.out.println("messages.length > " + messages.length);
if (messages.length > 0) {
InternetAddress[] autoResponseEmailAddress =
new InternetAddress[messages.length];
String autoResponseNames[] = new String[messages.length];
Inquiry[] emailInquiries = new Inquiry[messages.length];
String name = "", subject, emailAddress;
int index = 0;
System.out.println(" reading mails start ");
for (int j = (messages.length - 1); j > (-1); j--, index++) {
messages[j].setFlag(Flags.Flag.SEEN, true);
Address address = messages[j].getFrom()[0];
autoResponseEmailAddress[j] = (InternetAddress) address;
autoResponseNames[j] = autoResponseEmailAddress[j].getPersonal();
emailAddress = autoResponseEmailAddress[j].getAddress();
name = autoResponseNames[j];
subject = messages[j].getSubject();
System.out.println(" name " + name);
System.out.println(" subject " + subject);
}
}
folder.close(false);
store.close();
System.out.println("\n\ndone reading mails\n\n");
} catch (javax.mail.NoSuchProviderException nspe) {
logError(nspe);
} catch (MessagingException e) {
logError(e);
} catch (Exception exp) {
logError(exp);
}
}
}
Anything missing in above code ?
Please help.
Thanks in advance.
This happens due to gmail security features turned on by default.
To over come this issue do the following:
Sign in to your gmail account manually from web browser
goto https://www.google.com/settings/security/lesssecureapps - select Turn On
Google blocks authentication attempts. Try to login to Gmail account from a browser first. And make sure that you use the same account: https://accounts.google.com/b/0/DisplayUnlockCaptcha
Also add the following in your code:
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");