Sending email using javax? - java

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.

Related

How to send simple Email using Javamail?

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);
}
});

GAE not working for send mail using Send Grid using java

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.

Error while sending mails using smtp

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);
}

Java mail sender's address displayed rather than his name

I am trying to send mail to my friends through my Java Mail application. I am able to do it successfully however the receiver's column in the mailbox shows the complete email address rather than the name of the sender. I tried changing various parameters but still the mailbox would show the full e-mail address rather than the name of the sender.
using this method to send the message:
public void send(String key){
String to=key;
String from="mygmailid";
String subject="wassp";
String text="Hello";
Properties props=new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.user", "myname");
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 mailSession=Session.getDefaultInstance(props);
Message simpleMessage=new MimeMessage(mailSession);
InternetAddress fromAddress=null;
InternetAddress toAddress=null;
try{
fromAddress=new InternetAddress(from);
toAddress=new InternetAddress(to);
}
catch(AddressException e){
e.printStackTrace();
}
try{
simpleMessage.setFrom(fromAddress);
simpleMessage.setRecipient(RecipientType.TO,toAddress);
simpleMessage.setSubject(subject);
simpleMessage.setText(text);
transport.connect("smtp.gmail.com",465, "myid#gmail.com", "mygmailpassword");
transport.sendMessage(simpleMessage, simpleMessage.getAllRecipients());
transport.close();
}
catch(MessagingException e){
e.printStackTrace();
}
}
I am calling this method as:
public static void main(String[] args) {
MailSender mailer=new MailSender();
mailer.send("friendmail#gmail.com");
}
You can set a name in the InternetAddress using
new InternetAddress("mail#example.com", "Your Name");
You should use the two string constructor of InternetAddress to pass in both the e-mail address and the person's name. The resulting e-mail will contain a string like Jarrod indicated.
InternetAddress fromAddress=new InternetAddress("my#example.com", "John Doe");
try {
String from = " EMAIL ID";
String SMTP_AUTH_PWD = " PASSWORD ";
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.transport.protocol", "smtps");
props.put("mail.smtps.auth", "true");
String SMTP_HOST_NAME = "smtp.gmail.com";
int SMTP_HOST_PORT = 465;
javax.mail.Session mailSession = Session.getDefaultInstance(props);
mailSession.setDebug(true);
Transport transport = ((javax.mail.Session) mailSession)
.getTransport();
javax.mail.Message message = new MimeMessage(mailSession);
message.setSubject("Testing SMTP-SSL");
message.setContent("", "text/plain");
message.addRecipient(javax.mail.Message.RecipientType.TO,
new InternetAddress(receiver));
transport.connect(SMTP_HOST_NAME, SMTP_HOST_PORT, from,
SMTP_AUTH_PWD);
message.setFrom(new InternetAddress(from," YOUR PREFERED NAME "));
message.setSubject(subject);
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(body);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
message.setContent(multipart);
transport.sendMessage(message,
message.getRecipients(javax.mail.Message.RecipientType.TO));
}
How the from field is displayed is a client specific implementation detail.
Usually if the sender is in the form of "Sender Name" <sender#domain.com> the client will do the correct thing depending on configuration.
Some clients will infer the name information from their address book information if it is missing.
The answers above are correct but I found I needed to place in a try catch for it to work, here's what I found worked from sendemailwebapp demo application.
Message msg = new MimeMessage(session);
try {
msg.setFrom(new InternetAddress(userName, "YourName"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InternetAddress[] toAddresses = { new InternetAddress(toAddress) };
msg.setRecipients(Message.RecipientType.TO, toAddresses);
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setText(message);
Try this code within the try block.You can initialize your name within the setFrom() method of MimeMessage.
simpleMessage.setFrom(new InternetAddress("Your mail id", "Your name"));
ie,
try{
simpleMessage.setFrom(new InternetAddress("Your mail id", "Your name"));
simpleMessage.setRecipient(RecipientType.TO,toAddress);
simpleMessage.setSubject(subject);
simpleMessage.setText(text);
transport.connect("smtp.gmail.com",465, "myid#gmail.com", "mygmailpassword");
transport.sendMessage(simpleMessage, simpleMessage.getAllRecipients());
transport.close();
}
You can force to specify the sender's name by using the greater than and less than Symbol < > as per the following format:
String from="John Smith<friendmail#gmail.com>";
.
.
.
fromAddress=new InternetAddress(from);
or
public static void main(String[] args) {
MailSender mailer=new MailSender();
mailer.send("John Smith<friendmail#gmail.com>");
}
When receiving the email, the email recipient will see the name "John Smith" in his inbox. (Most email programs shows the name if specified. e.g. Outlook, gmail, hotmail, etc...)

Sending an email: Problem when connecting to host

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)

Categories