How to send simple Email using Javamail? - java

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

Related

Java Send E-Mail Using Gmail SMTP

Trying to send an email using my gmail account like bellow -
import org.junit.jupiter.api.Test;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class EMailTest {
#Test
public void sendEmail() {
String to = "to-email#markany.com";
String from = "from-email#gmail.com";
String host = "smtp.gmail.com";
Properties properties = System.getProperties();
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", "465");
properties.put("mail.smtp.ssl.enable", "true");
properties.put("mail.smtp.auth", "true");
Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, "from-email-password");
}
});
session.setDebug(true);
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("This is the Subject Line!");
message.setText("This is actual message");
System.out.println("sending...");
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
But it required turning on the "Less secure app access" option in sender/from email account setting.
And this option is no longer supported by Gmail -
https://support.google.com/accounts/answer/6010255?hl=en
So, how to send email now in Java using Gmail?

JavaxException Unknown SMTP host Exception: mail.gmail.com

I am trying to send mail using Java code . The code is working fine when running on my personal PC . But on office network the exception of unknown SMTP host is appearing. Also my office pc is not able to ping smtp.gmail.com. PC firewall is closed as well.
Is there any other way to establish the connection? I am also providing my code below for reference.
mport javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
import javax.mail.Authenticator;
public class otp {
String d_email = "email#gmail.com",
d_password = "password",
d_uname="uname",//your email password
d_host = "mail.outlook.com",
d_port = "587",
m_to = "target#gmail.com", // Target email address
m_subject = "Testing Mail programs",
m_text = "Hey, this is a test email.";
public otp() {
Properties props = new Properties();
props.put("mail.smtp.user", d_email);
props.put("mail.smtp.host", d_host);
props.put("mail.smtp.port", d_port);
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.debug", "true");
props.put("mail.smtp.socketFactory.port", d_port);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
try {
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getInstance(props,auth);
session.setDebug(true);
MimeMessage msg = new MimeMessage(session);
msg.setText(m_text);
msg.setSubject(m_subject);
System.out.println(1);
msg.setFrom(new InternetAddress(d_email));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m_to));
System.out.println(3);
Transport transport = session.getTransport("smtp");
transport.connect(d_host, Integer.valueOf(d_port),d_uname , d_password);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
Transport.send(msg);
System.out.println("Message Sent succesfully");
} catch (Exception mex) {
mex.printStackTrace();
}
}
public static void main(String[] args) {
otp blah = new otp();
}
private class SMTPAuthenticator extends javax.mail.Authenticator {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(d_email, d_password);
}
}
}
I guess that you are behind the internal firewall/proxy of your office, it is very common to put the whole internal network of a company behind a central firewall or to check Outgoing/Incoming requests of the networks traffic a Dynamic Proxy Server.in that case, you can check it in the proxy settings of your pc.
internet explorer(or any browser)-> settings -> internet option -> Connections Tab -> LAN Settings.
for the granular analyses,please attach your code.
you are using a gmail account but you have provided a outlook host , try the following template:
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendEmailUsingGMailSMTP {
public static void main(String[] args) {
// Recipient's email ID needs to be mentioned.
String to = "xyz#gmail.com";//change accordingly
// Sender's email ID needs to be mentioned
String from = "abc#gmail.com";//change accordingly
final String username = "abc";//change accordingly
final String password = "*****";//change accordingly
// >> gmail host
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(from));
// Set To: header field of the header.
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
// Set Subject: header field
message.setSubject("Testing Subject");
// Now set the actual message
message.setText("Hello, this is sample for to check send "
+ "email using JavaMailAPI ");
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException e) {
throw new RuntimeException(e);
}enter code here
}
}

apache james : mail server

The following is my code.
This executed successfully. But I didn't see any mail in my inbox
Anybody please help.
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class SendMail {
public static void main(String args[]) throws Exception {
String fromAddress = "testmail#gmail.com";
String toAddress = "testmail#gmail.com";
Properties properties = new Properties();
properties.put("mail.smtp.host", "localhost");
properties.put("mail.smtp.port", "25");
properties.put("mail.transport.protocol", "smtp");
try
{
properties.put("mail.smtp.starttls.enable", "true");
Session session = Session.getDefaultInstance(properties, null);
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(fromAddress));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toAddress));
message.setSubject("Email from our JAMEs");
message.setText("hiiiiii!!");
Transport.send(message);
System.out.println("Email sent");
}
catch (MessagingException e)
{
e.printStackTrace();
}
}
}
You'll need to either login and send over one of:
POP
IMAP
Gmail API
or you can use a domain you control, at the moment you are trying to send as gmail.com, and being ignored because it knows your IP is not allowed to send as gmail.com, because of SPF, which limits spam by setting who can send as which domains
SPF (Wikipedia)

Error when sending mail in Java

i have desktop application and i face this error when sending mail javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 587; nested exception is: java.net.ConnectException: Connection refused: connect
~code~
String host="smtp.mail.yahoo.com";
Properties props = new Properties();
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.smtp.host",host);
props.put("mail.smtp.host", host);
props.put("mail.stmp.user", "abc#yahoo.ca");//User name
//To use TLS
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.password", "mypassword"); //Password
props.put("mail.smtp.socketFactory.fallback", "false");
Session session1 = Session.getDefaultInstance(props, new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
String username = "abc#yahoo.ca";
String password = "mypassword";
return new PasswordAuthentication(username, password);
}
});
MimeMessage msg = new MimeMessage(session1);
String from = "abc#yahoo.ca";
String subject = "Testing...";
msg.setFrom(new InternetAddress(from));
msg.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(email));
msg.setSubject(subject);
Transport.send(msg);
YahooMail smtp port is 465 or 587
Add this :-
props.put("mail.smtp.port", "465");
or
props.put("mail.smtp.port", "587");
Did you find the JavaMail FAQ?
These entries will help:
How do I access Gmail with JavaMail?
How do I debug problems connecting to my mail server?
What are some of the most common mistakes people make when using JavaMail?
Try this:
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SendEmail
{
public static void main(String [] args)
{
// Recipient's email ID needs to be mentioned.
String to = "abcd#gmail.com";
// Sender's email ID needs to be mentioned
String from = "web#gmail.com";
// Assuming you are sending email from localhost
String host = "localhost";
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.setProperty("mail.smtp.host", host);
// Get the default Session object.
Session session = Session.getDefaultInstance(properties);
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("This is the Subject Line!");
// Now set the actual message
message.setText("This is actual message");
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}

Setting the "from" header field in Java MimeMessage not working correctly

For a web application I'm working on I made a method to send email notifications. The message has to come from a specific account, but I would like the "from" header field to read as an entirely different email address. Here is my code (I've changed the actual email addresses to fake ones):
public static boolean sendEmail(List<String> recipients, String subject, String content){
String header = "This is an automated message:<br />"+"<br />";
String footer = "<br /><br />unsubscribe link here";
content = header + content + footer;
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() {
//This is where the email account name and password are set and can be changed
return new PasswordAuthentication("ACTUAL.ADRESS#gmail.com", "PASSWORD");
}
});
try{
MimeMessage message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress("FAKE.ADDRESS#gmail.com", "FAKE NAME"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
message.setReplyTo(new Address[]{new InternetAddress("no-reply#gmail.com")});
for(String recipient: recipients){
message.addRecipient(Message.RecipientType.BCC,new InternetAddress(recipient));
}
message.setSubject(subject);
message.setContent(content,"text/html");
Transport.send(message);
return true;
}catch (MessagingException mex) {
mex.printStackTrace();
return false;
}
}
For the above method sending an email with it will have the following email header:
from: FAKE NAME <ACTUAL.ADRESS#gmail.com>
I want it to read:
from: FAKE NAME <FAKE.ADRESS#gmail.com>
What am I doing wrong? Any help is appreciated!
What you are looking to do is called "spoofing." It appears as though you are using Google's SMTP servers, if this is the case, you will not be able to do this successfully. For security purposes, Google will only allow the "from" address to be the authenticated email address.
See this related question

Categories