Send Email using gmail SMTP throwing AuthenticationFailedException - smtp

I am sending mail using smtp from my web site to gmail.its work well localy. But did't work in remote server
i am previously using this code:
public boolean sendMail(String subject, String bodyContent,String emailAddress){
boolean isMailsent=false;
final String SMTP_HOST= getText("email.smtp.host");
final String SOCKET_FACTORY_PORT= getText("email.socket.factory.port");
final String SMTP=getText("email.smtp.port");
final String MAIL_USER_EMAIL_ADDRESS=getText("email.username");
final String MAIL_USER_PASSWORD= getText("email.password");
final String EMAIL_FROMNAME= getText("email.fromname");
try{
Properties props = new Properties();
props.put("mail.smtp.host", SMTP_HOST);
props.put("mail.smtp.socketFactory.port",SOCKET_FACTORY_PORT);
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", SMTP);
Authenticator auth = new SMTPAuthenticator(MAIL_USER_EMAIL_ADDRESS, MAIL_USER_PASSWORD);
Session session = Session.getInstance(props, auth);
Message message = new MimeMessage(session);
InternetAddress from = new InternetAddress(MAIL_USER_EMAIL_ADDRESS,EMAIL_FROMNAME);
message.setFrom(from);
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(emailAddress));
message.setSubject(subject);
message.setContent(bodyContent,"text/html" );
Transport.send(message);
isMailsent=true;
}catch(Exception e){
LOGGER.error(e);
}
return isMailsent;
}
how to fix it please give me best example

You need to provide the correct GMail credentials to authenticate.

Related

Xamarin.Android - How to get JSON from website

I want to get JSON data from Site
Nothing shows up about it and Xamarin and I tried these 3 from youtube and it didn't work for me
public void ValidateNumber()
{
string URL = "http://android-householdinventory-api.epizy.com/ValidateNumber.php?";
WebClient client = new WebClient();
Uri uri = new Uri(URL + "number=10");
client.DownloadDataAsync(uri);
client.DownloadDataCompleted += Client_DownloadDataCompleted;
}
private void Client_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
{
//throw new NotImplementedException();
string json = Encoding.UTF8.GetString(e.Result);
System.Console.WriteLine(json);
}
public async void Validationv2()
{
using (var client = new HttpClient())
{
var uri = "http://android-householdinventory-api.epizy.com/ValidateNumber.php?number=100";
var Result = await client.GetStringAsync(uri);
System.Console.WriteLine(Result);
}
}
public void Validationv3()
{
WebClient wclient = new WebClient();
string a = wclient.DownloadString("http://android-householdinventory-api.epizy.com/ValidateNumber.php?number=100");
System.Console.WriteLine(a);
}
All Results to this:
<html><body><script type="text/javascript" src="/aes.js" ></script><script>function toNumbers(d){var e=[];d.replace(/(..)/g,function(d){e.push(parseInt(d,16))});return e}function toHex(){for(var d=[],d=1==arguments.length&&arguments[0].constructor==Array?arguments[0]:arguments,e="",f=0;f<d.length;f++)e+=(16>d[f]?"0":"")+d[f].toString(16);return e.toLowerCase()}var a=toNumbers("f655ba9d09a112d4968c63579db590b4"),b=toNumbers("98344c2eee86c3994890592585b49f80"),c=toNumbers("304feeb55638873348a9f20961a94049");document.cookie="__test="+toHex(slowAES.decrypt(c,2,a,b))+"; expires=Thu, 31-Dec-37 23:55:55 GMT; path=/"; location.href="http://android-householdinventory-api.epizy.com/ValidateNumber.php?number=10&i=1";</script><noscript>This site requires Javascript to work, please enable Javascript in your browser or use a browser with Javascript support</noscript></body></html>
How to fix this?
I'm new to c# and Xamarin
Your API server is returning HTML response for this "http://android-householdinventory-api.epizy.com/ValidateNumber.php?number=100" end point that's why it is showing HTML in response. You will have to correct the api response on server side.
try this! working example
private async void btn_Login_Clicked(object sender, EventArgs e)
{
List<LoginDetails> UserDetails = await _services.LoginAsync(string username, string password)
}
public async Task<List<LoginDetails>> LoginAsync(string username, string password)
{
List<LoginDetails> UserList;
using (var client = new HttpClient())
{
LoginDetails Ld = new LoginDetails();
Ld.UserName = username;
Ld.Password = password;
string url = "";
//HttpClient client = new HttpClient();
string jsonData = JsonConvert.SerializeObject(Ld);
StringContent content = new StringContent(jsonData, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(url, content);
string result = await response.Content.ReadAsStringAsync();
UserList = JsonConvert.DeserializeObject<List<LoginDetails>>(result);
//loginDetails = new ObservableCollection<LoginDetails>(UserList);
}
return UserList;
}
I was hosting on InfinityFree and it has aes.js so it may be causing that result.
This helped me in getting the solution
Setting Authorization Header of HttpClient
ByetHost server passing html values "Checking your browser" with JSON String
[I added this before client.GetAsync]
client.DefaultRequestHeaders.Add("Cookie", "__test=<COOKIE_CONTENT>; expires=<COOKIE_EXPIRATION>; path=/");

Javamail SMTPSenderFailedException 553

This code was working fine for months but has suddenly stopped working without any change in the code. The exception stack trace has:
com.sun.mail.smtp.SMTPSenderFailedException: 553 5.1.2 The address specified is not a valid RFC-5321 address. tj2sm1495299pab.4 - gsmtp
My code, which was working earlier:
final String username = uName;
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");
props.put("mail.smtp.debug", "true");
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("<from email id>"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("<to email address>"));
message.setSubject("<subject>");
message.setContent(finalMessage, "text/html");
Transport.send(message);
} catch (MessagingException | UnsupportedEncodingException e) {
e.printStackTrace();
logger.error("Emailing error: "+e.getMessage());
}
This stopped working today.
What did it for me was changing the username-field content from "username" to "username#gmail.com".
change the "from email id" for the complete email adress
Google has change the last week the validation from standar RFC 5321 that covers the field "FROM"

MySql Query Sent by Email

I have a simple query that select some fields from a few different tables and I need it to run once a month. I know i can schedule a monthly "job" with the CREATE EVENT, however, is it possible to have that information emailed to some addresses after the query runs? That way i don't need to log into the server and look at the new file?
I think that Mysql doesn't support Email sending.
In this case, you can develop an auxiliary program that sends the file created, and execute it with - scheduled task, Cron ...(It depends on the Operating System of the server you're using).
The auxiliary program can be like this code adding the file/s you want to attach (attachFiles variable).
public class EmailAttachmentSender {
public static void sendEmailWithAttachments(String host, String port,
final String userName, final String password, String toAddress,
String subject, String message, String[] attachFiles)
throws AddressException, MessagingException {
// sets SMTP server properties
Properties properties = new Properties();
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", port);
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.user", userName);
properties.put("mail.password", password);
// creates a new session with an authenticator
Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
};
Session session = Session.getInstance(properties, auth);
// creates a new e-mail message
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(userName));
InternetAddress[] toAddresses = { new InternetAddress(toAddress) };
msg.setRecipients(Message.RecipientType.TO, toAddresses);
msg.setSubject(subject);
msg.setSentDate(new Date());
// creates message part
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(message, "text/html");
// creates multi-part
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// adds attachments
if (attachFiles != null && attachFiles.length > 0) {
for (String filePath : attachFiles) {
MimeBodyPart attachPart = new MimeBodyPart();
try {
attachPart.attachFile(filePath);
} catch (IOException ex) {
ex.printStackTrace();
}
multipart.addBodyPart(attachPart);
}
}
// sets the multi-part as e-mail's content
msg.setContent(multipart);
// sends the e-mail
Transport.send(msg);
}
/**
* Test sending e-mail with attachments
*/
public static void main(String[] args) {
// SMTP info
String host = "smtp.gmail.com";
String port = "587";
String mailFrom = "your-email-address";
String password = "your-email-password";
// message info
String mailTo = "your-friend-email";
String subject = "New email with attachments";
String message = "I have some attachments for you.";
// attachments
String[] attachFiles = new String[3];
attachFiles[0] = "e:/Test/Picture.png";
attachFiles[1] = "e:/Test/Music.mp3";
attachFiles[2] = "e:/Test/Video.mp4";
try {
sendEmailWithAttachments(host, port, mailFrom, password, mailTo,
subject, message, attachFiles);
System.out.println("Email sent.");
} catch (Exception ex) {
System.out.println("Could not send email.");
ex.printStackTrace();
}
}
Mysql does not support that functionality.
You can use a cron job (Quartz) to schedule a job every month,
where you can fetch the data and shoot an email containing your data.
Refer the below link for quartz job :
http://www.mkyong.com/java/example-to-run-multiple-jobs-in-quartz/
is it possible to have that information emailed to some addresses
after the query runs?
If you are looking for a MySQL built in solution then probably NO. This particular should be handled in application end.
So, if you are scheduling the query as cron job in linux (OR) batch job in windows then you can configure cron (or) batch to send an email to list of recipients once the query finishes.
How to configure cron to send mail can be checked HERE
I haven't done this myself but I see no reason why it shouldn't work: create a UDF (user defined function) that takes the e-mail parameters and sends out the e-mail. You can write UDFs e.g. in C++ and have so all necesssary libraries at hand.

Send javamail using Office365

I'm having trouble configuring the SMTP settings for sending mail using javax.mail (1.4.4) through Office365, so I thought I'd post the properties here for others.
Use Office365 smtp details as below:
private static Properties props;
private static Session session;
static {
props = new Properties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.host", "m.outlook.com");
props.put("mail.smtp.auth", "true");
session = Session.getInstance(props, new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("office365 email address",
"office365 password");
}
});
}
And with spring-boot, you simply need to add this to your application.properties:
spring.mail.host = smtp.office365.com
spring.mail.username = mathieu.pousse#headquarter.com
spring.mail.password = s3cr3t
spring.mail.port = 587
spring.mail.properties.mail.smtp.auth = true
spring.mail.properties.mail.smtp.starttls.enable = true
A working code example:
Email email = new SimpleEmail();
email.setHostName("smtp.office365.com");
email.setSmtpPort(587);
email.setAuthenticator(new DefaultAuthenticator("a#b.com", "****"));
email.setStartTLSEnabled(true);
try {
email.setFrom("a#b.com");
email.setSubject("Job Failure");
email.setDebug(true);
email.setMsg("This is a test mail ... :-)" );
email.addTo("a#y.com");
email.send();
} catch (EmailException e) {
e.printStackTrace();
}
The only error that I am noticing in your code is the incorrect Host
javaMailProperties.setProperty("mail.smtp.from", "abc#c.com");
javaMailProperties.setProperty("mail.smtp.user", "abc#c.com");
javaMailProperties.setProperty("mail.smtp.password","Password");
javaMailProperties.setProperty("mail.smtp.host", "smtp.office365.com");
javaMailProperties.setProperty("mail.smtp.port", "587");
javaMailProperties.setProperty("mail.smtp.auth", "true");
javaMailProperties.setProperty("mail.smtp.starttls.enable", "true");
Change the host you will be all good.

Connecting SSIS WebService task to Spring WevService

I have a SSIS package in which i use a WebService task to call a Spring WS.
The authentication is done by client certificate and username & password.
I have tried to do it like this a simple HttpConnection and a WebService task - Error 504 Gateway Timeout. When i edit the HttpConnection and click on Test Connection i get an error that states:
"The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel."
I have tried doing it with a script task and the same error.
I have even tried with a dummy console application and the same result.
I also have a java written app that actually does the job but i do not have access to it's code-behind. This basically proves that the problem is not from the server itself.
The java application has it's own keystore and the same certificates that i have installed on the server.
I opened a wireshark capture and i saw that when i used either of my apps the host made a DNS request for an address that i did not configure anywhere(it seems like a proxy address from the intranet), while the java app made a DNS request with the correct address.
I am stuck here, and i have no idea what the problem might be or what else i can do so that i would get a proper error.
Please advise!
Edit:
This is the code that calls the WS:
public static void CallWebService()
{
var _url = "https://<IP>/App/soap/DataService";
string action = "getData";
Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters.Add("param1", "0");
parameters.Add("param2", "0");
parameters.Add("param3", "value");
XmlDocument soapEnvelopeXml = CreateSoapEnvelope(action, parameters);
HttpWebRequest webRequest = CreateWebRequest(_url);
InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest);
// begin async call to web request.
IAsyncResult asyncResult = webRequest.BeginGetResponse(null, null);
// suspend this thread until call is complete. You might want to
// do something usefull here like update your UI.
asyncResult.AsyncWaitHandle.WaitOne();
// get the response from the completed web request.
string soapResult;
using (WebResponse webResponse = webRequest.EndGetResponse(asyncResult))
{
using (StreamReader rd = new StreamReader(webResponse.GetResponseStream()))
{
soapResult = rd.ReadToEnd();
}
}
Console.WriteLine(soapResult);
}
private static HttpWebRequest CreateWebRequest(string url)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.ContentType = "text/xml;charset=\"utf-8\"";
webRequest.Accept = "text/xml";
webRequest.Method = "POST";
string thumbprint = "CERTIFICATE THUMBPRINT";
byte[] thumbprintArray = new byte[thumbprint.Split(new char[]{ ' ' }).Length];
string[] stringArray = thumbprint.Split(new char[] { ' ' });
for (int i = 0; i < thumbprintArray.Length; i++)
{
thumbprintArray[i] = Convert.ToByte(stringArray[i], 16);
}
X509Store localStore = new X509Store("My");
localStore.Open(OpenFlags.ReadOnly);
X509Certificate2Collection certCol = localStore.Certificates.Find(X509FindType.FindByTimeValid, DateTime.Now, true);
foreach (X509Certificate cert in certCol)
{
if (cert.GetCertHashString() == thumbprint)
{
webRequest.ClientCertificates.Add(cert);
break;
}
}
webRequest.UseDefaultCredentials = false;
webRequest.Credentials = new NetworkCredential("USER", "PASSWORD");
return webRequest;
}
private static XmlDocument CreateSoapEnvelope(string action, Dictionary<string, string> parameters)
{
string formatedParameters = string.Empty;
string paramFormat = "<{0}>{1}</{0}>";
foreach (string key in parameters.Keys)
{
formatedParameters += string.Format(paramFormat, key, parameters[key]);
}
XmlDocument soapEnvelop = new XmlDocument();
soapEnvelop.LoadXml(string.Format(#"
<soapenv:Envelope xmlns:soap=""http://custom/soap/"" xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"">
<soapenv:Header/>
<soapenv:Body>
<soap:{0}>
{1}
</soap:{0}>
</soapenv:Body>
</soapenv:Envelope>", action, formatedParameters));
return soapEnvelop;
}
private static void InsertSoapEnvelopeIntoWebRequest(XmlDocument soapEnvelopeXml, HttpWebRequest webRequest)
{
using (Stream stream = webRequest.GetRequestStream())
{
soapEnvelopeXml.Save(stream);
}
}