JavaMailSender can't send email when setting pc time to the past - java

I want to testing send mail using JavaMailSender,the code work fine but when I setting my pc time to the past it throw this exception.
Could not convert socket to TLS
Here is my code
MimeMessageHelper message = new MimeMessageHelper(mimeMessage, "UTF-8");
message.setSubject(subject);
message.setFrom(config.getMailFrom());
message.setTo(recipientEmail);
String htmlContent = templateEngine.process("email.html", ctx);
message.setText(htmlContent, true );
mailSender.send(mimeMessage);
catch (Exception e) {
throw new Exception();
}
I try to turn off the window defender but it didn't work.
My pc does not have any antivirus software or anything like protection software.It's
some kind of JavaMailSender protection or a bug?

Related

Connections with JavaMail

I am working with JavaMail for my plugin, within this plugin I am trying to send an email but my issue lies around the client. The client can't handle the plugin connecting to the email server and sending an email it either crashes the entire server or the client gets kicked out. My fix for this was instead of constantly connecting to the email server and sending an email why not simply keep one connection open when the plugin starts and grab that connection when I am wanting to send an email hopefully this will help in allowing the client and server to stay stable without any crashes. If anyone can help me I am just curious on how I can go about keeping a a single connection open and grabbing it when it is needed and then closing it when the plugin gets disabled.
What I have tried:
private Session session;
public void connect() {
String provider = plugin.getConfig().getString("EmailProvider");
String email = plugin.getConfig().getString("Email");
String password = plugin.getConfig().getString("Password");
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", provider);
props.put("mail.smtp.port", "25");
session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(email, password);
}
});
}
private boolean checkSession() {
try {
if (session != null) {
return true;
} else {
return false;
}
}
return false;
}
public void sendEmail(String to, String from, String subject, String text) {
if (!checkSession()) {
connect();
System.out.println("connecting");
}
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
message.setSubject(subject);
message.setText(text);
Transport.send(message);
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
The simple answer is, you can't.
There's no way to force a connection to remain open. Connections can be closed for all sorts of reasons and your program needs to be prepared for that.
You can, however, cache an open connection and reuse it as long as it's still connected. But without knowing what your plugin plugs in to, it's hard to describe the best strategy for that.
Note also that mail servers really don't want you to keep a connection open if you're not using it, which is why they'll close it out from under you if you leave it open but idle for too long. And artificially keeping the connection active won't win you any points with the mail server either.
If your mail server crashes when you connect to it, it's probably time to get a new mail server.

Mock mailBox by GreenMail

I try to mock server with mailbox to test mail send by another apllication.
I try to use GreenMail. I want to my test received mail send from some apllication.
This is my code in test:` ServerSetup setup = new ServerSetup(3025, "localhost", "smtp");
GreenMail greenMail = new GreenMail(setup);
greenMail.setUser("user1#mail.com", "user1", "user1");
greenMail.start();
greenMail.waitForIncomingEmail(50000, 1);
Message[] messages = greenMail.getReceivedMessages();
try {
System.out.println(messages[0].getSubject());
} catch (MessagingException e) {
e.printStackTrace();
}
}`
I run this code and send mail from my personal mailbox to adress "user1#mail.com". And mail doesn't reaches. Sombody know what I do wrong ?Please for help. Maybe i should use another tool for what I want achieve ?

javax.mail work on PC but not on server

I've search but can't seem to find a similar problem, never mind an answer. I have a web app running on my laptop (windows 8), tomcat7 and it works fine. It sends out the email as expected. I have the same code running on my linux server, also tomcat7 and I get javax.mail.AuthenticationFailedException.
I've done the Authenticator thing from the start:
...
Authenticator mailAuthenticator = new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(properties.getProperty("mail.smtp.user"),
properties.getProperty("mail.smtp.password"));
}
};
try {
// Get the default Session object.
Session session = Session.getInstance(properties, mailAuthenticator);
MimeMessage mimeMessage = new MimeMessage(session);
mimeMessage.setSubject("Subject, whoot whoot!");
mimeMessage.setFrom(new InternetAddress(properties.getProperty("mail.smtp.from")));
//This is an overkill
List<String> emailList = new LinkedList<>();
emailList.add("email#example.com");
for(String item : emailList) {
mimeMessage.addRecipients(Message.RecipientType.TO, InternetAddress.parse(item));
}
//The body ).(
StringBuilder sbMsg = new StringBuilder("Some text, etc.\n");
sbMsg.append("more text");
Multipart multipart = new MimeMultipart("alternative");
BodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setContent(sbMsg.toString(), "text/plain");
multipart.addBodyPart(messageBodyPart1);
mimeMessage.setContent(multipart);
Transport transport = session.getTransport(properties.getProperty("mail.transport"));
int port = Integer.parseInt(properties.getProperty("mail.smtp.port"));
//Exception happens on the line below
transport.connect(properties.getProperty("mail.smtp.host"),
port,
properties.getProperty("mail.smtp.user"),
properties.getProperty("mail.smtp.password"));
transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
return true;
} catch (Exception e) {
//Pokemon exception handling :(
LOG.log(Level.SEVERE, "Error while sending email", e);
}
The exception happens on transport.connect, and there is no description with the exception :(
I've checked the mail.smtp.user and mail.smtp.password and it is exactly the same :s
Any clues where I can start looking?
Just got an emails and text from Google. GMail thought I was trying to hack my account. I'm glad there is a logical answer to this problem :-)

Java Mail and Database connections are in conflict

This is my entire java code. If I comment the line:
objCon = DriverManager.getConnection(props.getString("url")); the mail is sending correctly. Else, its throwing the error - Could not connect to SMTP host: mail.companyname.com, port: 25;
public class PullRec {
private static final Logger LOG_TRACE = Logger.getLogger("debugLogger");
public static void main(String[] args) throws Exception {
Connection objCon = null;
PropertyResourceBundle props;
props = (PropertyResourceBundle) ResourceBundle.getBundle("com.cts.properties.config");
try {
Class.forName(props.getString("dbdriver"));
// If I comment the below line, the sendmail function works perfectly..!!
objCon = DriverManager.getConnection(props.getString("url"));
}
catch(Exception e) {
LOG_TRACE.info("DBConnection.java FILE ERROR: Disconnected due to "+e);
}
sendmail("Test");
}
public static void sendmail(String strBody) {
String to = "sarath#companyname.com";
String from = "sarath#companyname.com";
String host = "mail.companyname.com";
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
properties.setProperty("java.net.preferIPv4Stack","true");
Session session = Session.getDefaultInstance(properties);
try{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("CTS Monitor");
message.setContent(strBody,"text/html" );
Transport.send(message);
System.out.println("Sent message successfully....");
}
catch (MessagingException e) {
e.printStackTrace();
}
}
}
Your mail method is clearly setting the SMTP server hostname to "<hostname>". That is never going to work. You need to replace that with the real DNS hostname of the SMTP server you are attempting to use.
(Your from and to addresses are unlikely to work either ...)
If you have done that and it still isn't working, then check that you have got the (real) hostname and port correct, and that the SMTP server on that host / port are alive.
I notice that you have commented out the call to mail(String) which configures the mail server, and I'm not sure what your Mail object is, or what the sendmail method is actually doing.
(Note: this is NOT all of your Java code, because if it was, it doesn't compile!)

Mail sending is failed using java

I have used java mail API for sending mail in my application using java and web driver.My requirement is to send a mail whenever a link/url is down.Even though mail is send when i give url incorrectly ,but at the same time if a url is not loading due any other issue (page not found), found that mail is not getting send.
public void SendMail(String url,String str)
{
try
{
Sheet mailsheet = w.getSheet("mail");
String from = mailsheet.getCell(0,1).getContents().toString().trim();
String toEmailID=mailsheet.getCell(1,1).getContents().toString().trim();
Properties props = new Properties();
String mailprotocol = mailsheet.getCell(2,1).getContents().toString().trim();
String mailprotocoltype = mailsheet.getCell(3,1).getContents().toString().trim();
String mailhost = mailsheet.getCell(4,1).getContents().toString().trim();
String mailhostip = mailsheet.getCell(5,1).getContents().toString().trim();
String mailport=mailsheet.getCell(6,1).getContents().toString().trim();
String mailportid=mailsheet.getCell(7,1).getContents().toString().trim();
props.put(mailprotocol,mailprotocoltype);
props.put(mailhost,mailhostip);
props.put(mailport,mailportid);
javax.mail.Session mailSession =javax.mail.Session.getInstance(props);
Message msg = new MimeMessage(mailSession);
msg.setFrom(new InternetAddress(from));
msg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(toEmailID));
msg.setSubject("Test Summary");
msg.setContent("<html><body>Dear Admin,<br> Website page "+ "<b><i>"+url + "</b></i>"+" cannot be loaded due to the following :<br> <br></body></html>"+str,"text/html");
Transport.send(msg);
System.out.println("Mail is successfully sent to Recipient address with Error information.");
}
catch(Exception e)
{
//System.out.println(e);
System.out.println("Mail cannot be send to Recipient address due to connection error");
}
}
public void x() {
SendMail(url,driver.getTitle());
}
The answer is probably in the bit of code you don't show us : the part where you test the URL.
The response code for a wrong domain name is different from the response code due to a page not found. Also, depending on the system you're targetting, it's possible that page not found are redirected to the index page, making detection even more difficult.

Categories