I've been working on a prj(using JAVA SMTPAPI) in which I have to write a program for connectivity with SMTP. I have written a program using help of Google. now plz what I have to do? I have no IDEA further.
any advice or help would be appritiated
I have got this code
package mypackage;
import javax.mail.*;
import java.util.*;
import javax.mail.internet.*;
public class Sendmail {
private String strstmp;
public String getStrstmp() {
return strstmp;
}
public void setStrstmp(String strstmp) {
this.strstmp = strstmp;
}
public void sendMail( String recipients[ ], String subject, String message , String from)
{
// TODO Auto-generated method stub
boolean debug = false;
//set the host smtp addrs
Properties props = new Properties();
props.put("mail.smtp.host",getStrstmp());
//get default session
Session session = Session.getDefaultInstance(props, null);
session.setDebug(debug);
//create a new message
Message msg = new MimeMessage(session);
//set the from and to addrs
InternetAddress addressFrom = new InternetAddress(from);
msg.setFrom(addressFrom);
InternetAddress[] addressto = new InternetAdrress[recipients.length];
for(i = 0;i<recipients.length;i++)
{
addressTo[i] = new InternetAddress(recipients[i]);
}
msg.setRecipients(Message.RecipientType.TO, addressTo);
// Setting the Subject and Content Type
msg.setSubject(subject);
msg.setContent(message, "text/plain");
//send message
Transport.send(msg);
}
}
now wat would be addrs of host?
how to do connectivity test ?
Thanks in advance
You need to have access to a SMTP Server. You can install one locally for tests, see search results!
Related
Original Post ~
I am trying to send an email through java but I am getting an error that says it couldn't connect to host, port: smtp.gmail.com, 547; timeout -1;
I am trying to send it through gmail and I have imported two jar files, which are java mail api download – https://javaee.github.io/javamail/ java activation jar download – https://mvnrepository.com/artifact/javax.activation/activation/1.1.1
It takes forever to run and once it finally does finish it show that error.I would appreciate any help, even if it is just pointing me to a YouTube video or another post on this website. Thank you in advance.
Updated Post~
I had a comment saying to use 587 instead of 547 so I changed it but I am now getting an javax.mail.AuthenticationFailedException: Username and password not accepted error. I have googled and even looked on stack overflow and they say to change a setting in my google account but when I go to change it google is saying the setting is no longer available... it is the Less Secure app access.
I will love any thoughts or direction on how to fix this problem. I am on a Mac if anyone thinks that could be causing a problem.
import javax.mail.*;
import javax.mail.internet.*;
import java.io.IOException;
import java.util.Properties;
public class Mail {
Session newSession = null;
MimeMultipart multiPart = new MimeMultipart();
MimeMessage mimeMessage = new MimeMessage(newSession);
public static void main(String[] args) throws MessagingException, IOException, AddressException {
Mail mail = new Mail();
mail.setupServerProperties();
mail.draftEmail();
mail.sendEmail();
}
private void setupServerProperties() {
Properties properties = System.getProperties();
properties.put("mail.smtp.port", "587"); //was 547 changed // to 587
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
newSession = Session.getDefaultInstance(properties, null);
}
private MimeMessage draftEmail() throws AddressException, MessagingException, IOException {
String[] emailRecipients = {"abcd#gmail.com", "abcde#gmail.com"}; //who it is going to
String emailSubject = "Test Mail";
String emailBody = "Test body of email";
for(int i =0; i< emailRecipients.length; i++ ){
mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(emailRecipients[i]));
System.out.println("This is i" + i);
}
MimeBodyPart bodyPart = new MimeBodyPart();
bodyPart.setContent(emailBody, "html/text");
multiPart.addBodyPart(bodyPart);
mimeMessage.setContent(multiPart);
return mimeMessage;
}
private void sendEmail() throws MessagingException{
String fromUser = "yourPersonalEmail#gmail.com"; //sender
String fromUserPassword = "yourPassword"; //Password for senders email
String emailHost = "smtp.gmail.com";
Transport transport = newSession.getTransport("smtp");
transport.connect(emailHost, fromUser, fromUserPassword);
transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
transport.close();
System.out.println("Email Successfully sent");
}
}
I am developing an application that needs to pull specific filtered messages. I also need to be able to exclude certain messages. for instance, a user may want to exclude all message with the subject, which in this case I would create a SubjectTerm, and put it inside a NotTerm. This is returning 0 messages for some reason. while when i ask just for the subject term, it returns the correct message.The specific service i am trying to use this code with are yahoo and hotmail.
package javaapplication2;
import java.io.*;
import java.util.*;
import javax.mail.*;
import javax.mail.search.*;
public class imapyahoo {
public static void main(String[] args) {
//set the properties for an ssl connection to the imap server.
java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
Properties props = new Properties();
props.setProperty("mail.store.protocol", "imaps");
props.setProperty("mail.imap.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.imap.socketFactory.fallback", "false");
props.setProperty("mail.imap.socketFactory.port", "993");
try {
Session session = Session.getInstance(props, null);
Store store = session.getStore();
System.out.println("connecting....");
store.connect("imap.mail.yahoo.com", "account", "password");
System.out.println("connected");
System.out.println("searching inbox");
Folder inbox = store.getFolder("inbox");
inbox.open(Folder.READ_ONLY);
//apply the search term.
SearchTerm st = new NotTerm(new SubjectTerm("dogs"));
Message[] msgs =inbox.search(st);
System.out.println(msgs.length);
System.out.println("done searching");
//print out the messages
int i =1;
for (Message msg : msgs){
System.out.println(i);
System.out.println(msg.getSubject());
i++;
}
inbox.close(true);
store.close();
} catch (Exception mex) {
mex.printStackTrace();
}
}
}
I'm currently working on a project that involves the creation of a .jar file. The following is to be achieved, I'm supposed to export/read the path of a friend's registry, once this is done I'm supposed to get the result back via email. The whole concept is in creating the jar file and once it's clicked I get the results through my email since I actually sent it through email.
(I hope this makes sense)
So first, I've combined the following code to actually read the registry and display the keys ( i got it from the popular post on stack overflow for read/write registries) so the reading process is working fine, now my problem is with the email code,
(I'm not quite sure who the original owner to this code is but full credit goes it him)
I'm trying to get the basic concept of this email code to work so that I can continue working on sending my jar file as an attachment and link it to my code in a way when a user clicks on the jar file, the registry results will be emailed back to me.
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.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class MailCode {
public static void main(String[] args) throws Exception {
final String smtp_host = "smtp.gmail.com";
final String smtp_username = "user#gmail.com";
final String smtp_password = "password";
final String smtp_connection = "TLS"; // Use 'TLS' or 'SSL' connection
final String toEmail="tomail#hotmail.com";
final String fromEmail="**#gmail.com";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
if (smtp_connection.equals("TLS")) {
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.port", "587");
} else{
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.port", "465");
}
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(smtp_username, smtp_password);
}
});
try {
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(fromEmail, "NoReply"));
msg.addRecipient(Message.RecipientType.TO,
new InternetAddress(toEmail, "Mr. Recipient"));
msg.setSubject("Welcome To JavaMail API");
msg.setText("JavaMail API Test - Sending email example through remote smtp server");
Transport.send(msg);
System.out.println("Email sent successfully...");
} catch (AddressException e) {
throw new RuntimeException(e);
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
This is the error message I'm getting:
Exception in thread "main" java.lang.RuntimeException: javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 587;
nested exception is:
java.net.SocketException: Permission denied: connect
The following code may help you to solve your problem, its working........
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class Email {
private static String USER_NAME = "username"; // GMail user name (just the part before "#gmail.com")
private static String PASSWORD = "password"; // GMail password
private static String RECIPIENT = "xxxxx#gmail.com";
public static void main(String[] args) {
String from = USER_NAME;
String pass = PASSWORD;
String[] to = { RECIPIENT }; // list of recipient email addresses
String subject = "Java send mail example";
String body = "hi ....,!";
sendFromGMail(from, pass, to, subject, body);
}
private static void sendFromGMail(String from, String pass, String[] to, String subject, String body) {
Properties props = System.getProperties();
String host = "smtp.gmail.com";
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.ssl.trust", 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");
Session session = Session.getDefaultInstance(props);
MimeMessage message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(from));
InternetAddress[] toAddress = new InternetAddress[to.length];
// To get the array of addresses
for( int i = 0; i < to.length; i++ ) {
toAddress[i] = new InternetAddress(to[i]);
}
for( int i = 0; i < toAddress.length; i++) {
message.addRecipient(Message.RecipientType.TO, toAddress[i]);
}
message.setSubject(subject);
message.setText(body);
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
catch (AddressException ae) {
ae.printStackTrace();
}
catch (MessagingException me) {
me.printStackTrace();
}
}
}
You're setting smtp_host but you're never using it.
javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 587;
You're trying to connect to 'localhost' instead of gmail.com. That's becase you're not setting mail.smtp.host anywhere.
And why are you setting an SSL socket factory in the non-TLS case?
Please check your Antivirus/Malware.
If you are using corporate developer machine please contact your administrator to remove that access protection rule.
I had the same problem, my McAfee was blocking all the request.
Blocked by port blocking rule C:\PROGRAM FILES\JAVA\JDK1.8.0_74\BIN\JAVAW.EXE Anti-virus Standard Protection:Prevent mass mailing worms from sending mail 0:0:0:0:0:ffff:4a7d:7e6d:587
found this in Access protection log and requested my admin to remove that rule.
Try this might help you.
I have a code which connects to a mailserver and searches for a particular subject tag and sends response back (REPLY) to that particular mail.
However while giving a reply message I get the following error :
Could not connect to SMTP host: localhost, port: 25
I am able to send email directly the problem occurs only if i use REPLY/FORWARD method.I am using javamail.
import java.util.*;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.search.SearchTerm;
import javax.mail.search.SubjectTerm;
public class Mail {
public static void main(String args[]) throws Exception {
Properties properties = System.getProperties();
Session session = Session.getDefaultInstance(properties);
Store store = session.getStore("pop3");
store.connect("smtp.gotouchpoint.com", "username", "password");
Folder folder = store.getFolder("inbox");
//Connect to the current host using the specified username and password.
try {
//Create a Folder object corresponding to the given name.
// Folder folder = store.getFolder("INBOX");
// Open the Folder.
folder.open(Folder.READ_WRITE);
SearchTerm st1 =new SubjectTerm("**NEW-TICKET**");
Message[] message = folder.search(st1);
//Message[] message = folder.getMessages();
// Create a reply message
for (int i = 0; i < message.length; i++) {
System.out.println("------------ Message " + (i + 1) + " ------------");
System.out.println("SentDate : " + message[i].getSentDate());
System.out.println("From : " + message[i].getFrom()[0]);
System.out.println("Subject : " + message[i].getSubject());
if(message[i].getSubject().equals("**NEW-TICKET**")) {
System.out.println("new-ticket");
Message forward = new MimeMessage(session);
// Fill in header
forward.setSubject("Fwd: " + message[i].getSubject());
forward.setFrom(new InternetAddress(message[i].getFrom()[0].toString()));
forward.addRecipient(Message.RecipientType.TO,
new InternetAddress("techsupport#touchpointindia.com"));
// Create your new message part
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("Oiginal message:\n\n");
// Create a multi-part to combine the parts
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// Create and fill part for the forwarded content
messageBodyPart = new MimeBodyPart();
messageBodyPart.setDataHandler(message[i].getDataHandler());
// Add part to multi part
multipart.addBodyPart(messageBodyPart);
// Associate multi-part with message
forward.setContent(multipart);
System.out.println("msg forward ...." +forward.getSubject());
// Send message
Transport.send(forward);
}
}
System.out.println();
folder.close(true);
store.close();
}catch(Exception e) {
e.printStackTrace();
}
}
}
Not sure what might be causing your error.
I'm just taking a wild guess here: Don't use the static Transport.send() method.
Get a transport object and invoke it's sendMessage) method:
[...]
Transport transport = session.getTransport("smtp");
transport.connect(D_HOST, D_PORT, D_USER, D_PASS);
transport.sendMessage(forward, forward.getAllRecipients());
Try and see if this helps.
cheers.
Here's the code I have installed at the top of my document:
copied from: http://coders-and-programmers-struts.blogspot.com/2009/05/sending-email-using-javamail-e-mailing.html
package my.planterstatus;
import java.awt.event.ActionEvent;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
import javax.activation.*;
/**
*
* #author Kris
*/
public class PlanterStatusUI extends javax.swing.JFrame
{
/** Creates new form PlanterStatusUI */
public PlanterStatusUI() {
initComponents();
}
public String status = new String(); {
}
public class TestEmail {
// Send a simple, single part, text/plain e-mail
public void main(String[] args, String status) {
// SUBSTITUTE YOUR EMAIL ADDRESSES HERE!!!
String to = "blah#blahblahblah.com";
String from = "Planter Status";
// SUBSTITUTE YOUR ISP'S MAIL SERVER HERE!!!
String host = "smtp.blahblah.com";
// Create properties, get Session
Properties props = new Properties();
// If using static Transport.send(),
// need to specify which host to send it to
props.put("pop.blahblah.net", host);
// To see what is going on behind the scene
props.put("mail.debug", "true");
Session session = Session.getInstance(props);
try {
// Instantiatee a message
Message msg = new MimeMessage(session);
//Set message attributes
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = {new InternetAddress(to)};
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject("PS# " + display.getText()+ " is currently " + status);
msg.setSentDate(new Date());
// Set message content
msg.setText("PS# " + display.getText()+ " is currently " + status);
//Send the message
Transport.send(msg);
}
catch (MessagingException mex) {
// Prints all nested (chained) exceptions as well
mex.printStackTrace();
}
}
}//End of class
and here's the code I have installed in my button's event handler:
private void confirmationYesButtonHandler(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
Transport.send(msg);
}
The error message I get from netbeans is:
"cannot find variable msg"
The 2 options NetBeans gives me to "solve" the issue are:
"Create Field msg in my.planterstatus.PlanterStatusUI"
"Create Local Variable msg"
I don't know how to fix this. From my extremely limited understanding of Java, it looks like the "msg" variable has been fleshed out at the top of the document, but apparently not.
Help is appreciated!
The scope of the msg variable you've shown is limited to the try block it is within.
Here's a page from the "Java Made Easy" tutorial on scope that appears fairly easy to understand.
msg is declared in the try block and thus is only visible in the try block.