JavaMail SMTPSendFailedException - smtp

I am writing a bulk email program using the JavaMail api. I have a Microsoft Exhange server which I am trying to send the emails in to. When I run my program I get the following error:
**com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:2057)
at com.sun.mail.smtp.SMTPTransport.finishData(SMTPTransport.java:1862)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1100)
at javax.mail.Transport.send0(Transport.java:195)
at javax.mail.Transport.send(Transport.java:124)
at SendEmail.postMail(SendEmail.java:100)
at EmailGenerator.main(EmailGenerator.java:52)**
The part of my code trying to send the message is as follows:
Properties props = new Properties();
props.put("mail.smtp.host", email_server);
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", true);
class EmailAuthenticator extends Authenticator {
String user;
String pw;
EmailAuthenticator (String FROM, String PASSWORD)
{
super();
this.user = FROM;
this.pw = PASSWORD;
}
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(user, pw);
}
}
Session session = Session.getInstance(props, new EmailAuthenticator(USER, PASSWORD));
session.setDebug(debug);
System.out.println("Session created");
.. CREATED MESSAGE HERE...
Transport transport = session.getTransport("smtp");
transport.connect(exchange_server,user,password);
transport.send(msg);
transport.close();
I wonder am I missing some configuration on the Exchange server side, or is an issue with my code?

OK I figured out where I was going wrong here and am posting up the answer incase anybody else can get some value out of it. I had the following line of code:
props.put("mail.smtp.auth", true);
This was telling my application that it needed to authenticate to the SMTP server, when in fact it didnt. This was causing my application from logging into the SMTP server and sending the email and thus producing the error message. Setting this property to false or not having this line of code fixed the issue for me. This line of code is only necessary for SMTP servers that require you to login, which my Exchange server didnt.

Related

Showing error or success message on same page

this is my first time posting here since I couldn't figure the issue out, please keep in mind im fairly new to Spring and not that good at Java and coding in general.
I'm trying to program a Server application with Java Spring where you're able to create different accounts with specific roles. I want my users to be able to see a success or error message on the same page if the creation of an account succeded or failed.
Right now I'm using the error.param th:if tag from https://spring.io/guides/gs/securing-web/
the specific code in my HTML file is:
<div id="error" th:if="${param.error}">
Benutzername existiert bereits.
</div>
<div id="success" th:if="${param.success}">
Das Konto wurde erfolgreich erstellt.
</div>
Which works when I manually put ?success or ?error behind my URL.
I map my POST to the database by this method:
#PostMapping("/create/lieferant/fahrer")
public String submitDriver(#ModelAttribute Driver driver){
if(userRepository.existsByUsername(driver.getUsername())){
return "create/lieferant/fahrer?error";
}
Driver d = new Driver();
User n = new User();
Role r = new Role();
d.setName(driver.getName());
d.setTelnum(driver.getTelnum());
d.setUsername(driver.getUsername());
n.setUsername(driver.getUsername());
n.setPassword(encoder().encode(driver.getPassword()));
r.setUsername(driver.getUsername());
r.setAuthority("LIEFERANT");
userRepository.save(n);
driverRepository.save(d);
roleRepository.save(r);
return "create/lieferant/fahrer?success";
}
The idea is to check if the username is already registered and if so, returning the create/lieferant/fahrer?error but it says
Error resolving template "create/lieferant/fahrer?error", template
might not exist or might not be accessible by any of the configured
Template Resolvers
and the same for ?success.
What I don't understand is: it's working for the login which I've gotten from the Spring getting started guide and it seems to be working without any heavy configurations or so. Atleast I don't see any.
I'd be glad if anyone could help me figuring my issue out.
Thanks a lot.
You could do something like this:
#PostMapping("/create/lieferant/fahrer")
public ModelAndView submitDriver(#ModelAttribute Driver driver){
ModelAndView mav = new ModelAndView();
mav.setViewName("create/lieferant/fahrer");
try {
if(userRepository.existsByUsername(driver.getUsername())){
return "create/lieferant/fahrer?error";
}
Driver d = new Driver();
User n = new User();
Role r = new Role();
d.setName(driver.getName());
d.setTelnum(driver.getTelnum());
d.setUsername(driver.getUsername());
n.setUsername(driver.getUsername());
n.setPassword(encoder().encode(driver.getPassword()));
r.setUsername(driver.getUsername());
r.setAuthority("LIEFERANT");
userRepository.save(n);
driverRepository.save(d);
roleRepository.save(r);
mav.addObject("success", "All was ok");
} catch (Exception e) {
mav.addObject("error", "Error message to change");
}
return "create/lieferant/fahrer?success";
}
You could retrieve messages on page with the two keys "success" and "error"

Database logon failed while using mysql azure

I am trying to print crystal report in PDF format , and on my local machine it’s working fine. But when I publish application to the server, it’s giving me the following error on Print button.
Exception Details: System.Runtime.InteropServices.COMException: Database logon failed.
Below is my code in my controller
public ActionResult Export(int Id)
{
ReportDocument rd = new ReportDocument();
rd.Load(Path.Combine(Server.MapPath("~/Reports/GcReport.rpt")));
var query = rLAService.GetGeneralConsignmentById(Id);
var querylist = new List<GeneralConsignmentDto> { query };
rd.SetDataSource(querylist);
rd.SetParameterValue("Id", Id);
//rd.SetDataSource(rLAService.GetGeneralConsignmentById(Id));
Response.Buffer = false;
Response.ClearContent();
Response.ClearHeaders();
Stream stream = rd.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
stream.Seek(0, SeekOrigin.Begin);
return File(stream, "application/pdf", "GC Report.pdf");
}
Edit
Ok, after digging throuh the problem, i found that error is table name generalconsignment1 does not found. But problem is it is taking automatically instead of generalconsignment.now how to handle this situation?

Should a server always send a JSON object as an http response?

I'm working on a node.js server using express and a android native app, using Retrofit 1.9.
For a login API that returns only a true/false answer to the client, should JSON still be used?
As I see it, the server has only to send a status code response:
if(isLegal) {
res.sendStatus(200);
dbConnector.updateUser(token);
}
else{
console.log('Token is not legal');
res.sendStatus(403);
}
But the Retrofit framework tries to convert the response to JSON, which makes me think I must send a JSON object with the answer, though it seems weird.
My retrofit restClient:
public class RestClient {
private static final String URL = SessionDetails.getInstance().serverAddress;
private retrofit.RestAdapter restAdapter;
private ServerAPI serverAPI;
public RestClient() {
restAdapter = new retrofit.RestAdapter.Builder()
.setEndpoint(URL)
.setLogLevel(retrofit.RestAdapter.LogLevel.FULL)
.build();
serverAPI = restAdapter.create(ServerAPI.class);
}
public ServerAPI getService() {
return serverAPI;
}
}
And usage:
restClient.getService().login(token.getToken(), token.getUserId(), new Callback<Void>() {
#Override
public void success(Void aVoid, Response response) {
Log.d("Chooser", "Successful login on server.");
}
#Override
public void failure(RetrofitError error) {
error.printStackTrace();
Log.d("Chooser", "Login failed on server.");
}
});
Using it as it is results with the following error:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING
There are many topics on this issue but no certain answer about the correct (or better) method to use.
Any ideas about the best implementation in these cases?
Sending an empty body with your HTTP response is perfectly legal and some clients may care only about the response status but some clients may expect to get a response so sending a body never hurts and sometimes may be useful.
You can include a JSON response in addition to the HTTP response status:
// Express 4.x:
res.status(403).json({error: 'Token is not legal'});
// Express 3.x:
res.json(403, {error: 'Token is not legal'});
Such an error message can be very useful for the client development. You can get 403 for many reasons, illegal token, expired token, a legal not expired token but for the wrong user that doesn't have some privilege - adding a specific error message in addition to the HTTP response code can tell the client what exactly went wrong and allows the client-side code to show a better error message to the user.
Also, note that true and false are also valid JSON.

Javamail fail with an authentication Exception, why?

I'm working in a Java EE webApplication and I hope to send emails to my clients.
So I add mail.jar and activation.jar and I tried this simple code:
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
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 SendHTML {
static Properties mailServerProperties;
static Session getMailSession;
static MimeMessage generateMailMessage;
public static void main(String args[]) throws AddressException, MessagingException {
generateAndSendEmail();
System.out.println("\n\n ===> Your Java Program has just sent an Email successfully. Check your email..");
}
public static void generateAndSendEmail() throws AddressException, MessagingException {
//Step1
System.out.println("\n 1st ===> setup Mail Server Properties..");
mailServerProperties = System.getProperties();
mailServerProperties.put("mail.smtp.port", "587"); // TLS Port
mailServerProperties.put("mail.smtp.auth", "true"); // Enable Authentication
mailServerProperties.put("mail.smtp.starttls.enable", "true"); // Enable StartTLS
System.out.println("Mail Server Properties have been setup successfully..");
//Step2
System.out.println("\n\n 2nd ===> get Mail Session..");
getMailSession = Session.getDefaultInstance(mailServerProperties, null);
generateMailMessage = new MimeMessage(getMailSession);
generateMailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress("Recipient#gmail.com"));
generateMailMessage.addRecipient(Message.RecipientType.CC, new InternetAddress("Recipient#gmail.com"));
generateMailMessage.setSubject("Greetings from me..");
String emailBody = "Test email by me JavaMail API example. " + "<br><br> Regards, <br>Admin";
generateMailMessage.setContent(emailBody, "text/html");
System.out.println("Mail Session has been created successfully..");
//Step3
System.out.println("\n\n 3rd ===> Get Session and Send mail");
Transport transport = getMailSession.getTransport("smtp");
// Enter your correct gmail UserID and Password
transport.connect("smtp.gmail.com", "myusername#gmail.com", "mypassword");
transport.sendMessage(generateMailMessage, generateMailMessage.getAllRecipients());
transport.close();
}
}
So Step1 and Step2 work successfully, but Step3 generate an Authentication exception:
1st ===> setup Mail Server Properties..
Mail Server Properties have been setup successfully..
2nd ===> get Mail Session..
Mail Session has been created successfully..
3rd ===> Get Session and Send mail
Exception in thread "main" javax.mail.AuthenticationFailedException
at javax.mail.Service.connect(Service.java:264)
at javax.mail.Service.connect(Service.java:134)
at entity.SendHTML.generateAndSendEmail(SendHTML.java:53)
at entity.SendHTML.main(SendHTML.java:24)
Please can someone help me to fixe the problem ?
First, there is nothing named "JEE", you meant "Java EE".
If you're using Java EE, you shouldn't need mail.jar and activation.jar, they're already part of every Java EE server.
You're going to want to read these JavaMail FAQ entries on common mistakes and how to debug JavaMail applications.
AuthenticationFailedException means the server doesn't like your username and password.
You're probably running into the problem described here.

Getting the cannot callsendredirect() after the response has been committed

Again my question related with the same project which i am doing for the report tracking system getting the below error in the tomcat logs after accessing the login page which is redirect towards "userloginmid.jsp".The code as shown below in the same window.
Please provide the solution for the same if possible.
<%# page import="java.sql.*,java.util.*,java.text.*,java.text.SimpleDateFormat" %>
<%
String userName = request.getParameter("userName");
String password = request.getParameter("password");
System.out.println("MySQL Connect Example.");
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "report_tracking";
String driver = "com.mysql.jdbc.Driver";
String username = "root";
String userPassword = "root";
java.util.Date now = new java.util.Date();
String DATE_FORMAT = "yyyy-MM-dd hh:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
String strDateNew = sdf.format(now) ;
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,username,userPassword);
Statement st = conn.createStatement();
String strQuery = "select * from userregister where username='"+userName+"' and password='"+password+"'";
out.println(strQuery);
ResultSet rs = st.executeQuery(strQuery);
if(rs.next())
{
int userid=rs.getInt(1);
String user=rs.getString(2);
session.setAttribute("userid",userid);
session.setAttribute("username",user);
session.setAttribute("intime",strDateNew);
String queryString = "INSERT INTO admin set userid="+userid+",intime='"+strDateNew+"'";
int i = st.executeUpdate(queryString);
if(i>0)
{
response.sendRedirect("welcome.jsp");
}
}
response.sendRedirect("login.jsp");
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
%>
As all said there are lot of loopholes in your code.
But the answer to your quesion is
sendRedirect requires a return statement
So change your lines of code to
response.sendRedirect( "welcome.jsp"); return; and
response.sendRedirect("login.jsp"); return;
Also read this .
There are a lot of problems with your code.
First, the explanation of your stated problem, redirecting after committing a response:
When the HTTP headers are already sent to the client (read about the HTTP protocol if you don't know it yet), they are out and cannot be pulled back. You're coding your sample in a jsp, which is the VIEW part of your architecture - and at least between the "page import" and the code part there's a newline which might trigger the server to flush its buffers to the client. Once that's done, the HTTP headers are gone and you cannot redirect any more.
Workaround: Don't implement this routine in a jsp, but in a servlet (or use a decent framework that handles this problem for you. Any of the current will suffice).
Now about some of the problems that your code has:
Please read about SQL injection. Think of someone posting
usernames like someone'; someone' OR '0' = '0 or similar (just
making them up as I go)
Once you get your connection and run in to any error, you won't clean
up the connection (e.g. you will leak connections on any exception)
You seem to be storing clear text passwords. Definitely a no-go as
soon as someone else than you will have an account