SMTP Sending multiple emails - email

I have to send reminder emails to about 150 people 1st of every month.
It seemed to be working fine, but this month... I started to get
Caused by: javax.mail.AuthenticationFailedException: 421 4.3.2 Service not active [BN6PR1801CA0007.namprd18.prod.outlook.com]
at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:965) ~[javax.mail-1.6.2.jar!/:1.6.2]
at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:876) ~[javax.mail-1.6.2.jar!/:1.6.2]
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:780) ~[javax.mail-1.6.2.jar!/:1.6.2]
at javax.mail.Service.connect(Service.java:366) ~[javax.mail-1.6.2.jar!/:1.6.2]
this error message all of sudden.
It still works fine sending to small number of people.
When I try for big number of people, it sends to about 10 people and throws that error.
Then, it sends the rest emails few minutes later; however, it seems to not end the loop properly because of the error.
---application.properties---
spring.mail.host=smtp.office365.com
spring.mail.port=587
spring.mail.protocol=smtp
spring.mail.username=xx#xxxx.com
spring.mail.password=xxxxxx
spring.mail.properties.mail.transport.protocol=smtps
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtps.timeout=8000
---sending method---
public void sendEmail(String tok, String email, int file, String msg, String to) throws UnsupportedEncodingException, MessagingException, FileNotFoundException
{
FilePath fp = new FilePath();
String token = tok;
String recipientAddress = email;
String subjectConfirm = "Confirm " + to;
String subjectAlert = "Alert " + to;
String confirmationUrl = fp.getServer() + "/to/filesConfirm?token=" + token;
String message = msg;
MimeMessagePreparator preparator = new MimeMessagePreparator() {
public void prepare(MimeMessage mimeMessage) throws Exception {
mimeMessage.setRecipient(Message.RecipientType.TO,
new InternetAddress(recipientAddress));
mimeMessage.setFrom(new InternetAddress("xx#xxxx.com"));
if (file > 0)
{
mimeMessage.setSubject(subjectConfirm);
mimeMessage.setContent(message + "<br>" + "<a target='_blank' href="+confirmationUrl+"><button>Confirm</button></a>"
+ "<br>" + "If the button above doesn't work, please click or copy&paste the address below to 'Confirm'."
+ "<br>" + confirmationUrl, "text/html;charset=UTF-8");
}
else
{
mimeMessage.setText(message);
mimeMessage.setSubject(subjectAlert);
}
}
}; this.mailSender.send(preparator);
}

I've fixed it by switching the host to amazon

Related

Submitting POST request to Facebook Messenger API

I'm struggling to connect to the Facebook Messenger API. The server keeps returning:
The remote server returned an error: (400) Bad Request.
I've been at this for a few days, tried multiple methods, even tried a few VS packages that don't quite work. I've checked my Auth Token several times, and I don't know what else it might be.
Is there something obvious that's causing a bad request? I've copied the root URL from Facebook's API page. The token in the code below has been removed. The application throws an exception when I attempt to read the response. (WebResponse FBresponse = FBrequest.GetResponse();)
private string FBSendMessage(string user, string message)
{
string result = null;
string FBroot = "https://graph.facebook.com/v2.6/me/messages?access_token=";
string token = "EAA...DZD";
string FBURI = FBroot + token;
string FBstring = "{ \"recipient\": { \"id\":\"" + user + "\" }, \"message\": { \"text\":\"" + message + "\" } }";
try
{
//using (WebClient FBclient = new WebClient())
//{
// result =
// FBclient.UploadString(FBURI, FBstring);
//}
HttpWebRequest FBrequest = (HttpWebRequest)WebRequest.Create(FBURI);
FBrequest.Credentials = CredentialCache.DefaultCredentials;
FBrequest.ProtocolVersion = HttpVersion.Version11;
FBrequest.Method = "POST";
FBrequest.ContentType = "application/json";
byte[] FBbytes = Encoding.UTF8.GetBytes(FBstring);
FBrequest.ContentLength = FBbytes.Length;
Stream FBstream = FBrequest.GetRequestStream();
FBstream.Write(FBbytes, 0, FBbytes.Length);
FBstream.Close();
WebResponse FBresponse = FBrequest.GetResponse();
Output((((HttpWebResponse)FBresponse).StatusDescription), Log.Error);
FBstream = FBresponse.GetResponseStream();
StreamReader FBreader = new StreamReader(FBstream);
result = FBreader.ReadToEnd();
FBreader.Close();
FBresponse.Close();
}
catch(Exception ex)
{
Output(ex.Message, Log.Error);
}
return result;
}
I have determined that my code isn't the issue. The issue is that I'm making a request with an invalid user id. Facebook creates a user ID in the application context that isn't the same as your default user id. I have to receive a message to learn that contextualized id before I can send a message.

Google Cloud Storage XML API Policy document accessed through Google CloudEndpoint API. Lexical Error: Unmatched input

I am getting the following error
InvalidPolicyDocumentThe content of the
form does not meet the conditions specified in the policy
document.Policy document parsing error: Lexical
Error: Unmatched Input: <s>
My Async Task to call a HTTPURLConnection is below. The multipartv1 class is from here.
Inside an AsyncTask doinbackground
{multipartv1.addFormField("key", filename_insert_value);
multipartv1.addFormField("bucket", “myapplication”);
multipartv1.addFormField("Content-Type", "image/jpeg");
multipartv1.addFormField("GoogleAccessId", “myapplication#appspot.gserviceaccount.com");
multipartv1.addFormField("acl", "bucket-owner-read");
multipartv1.addFormField("success_action_redirect", "https://myapplication.appspot.com/getpolicydocumentsuccess");
multipartv1.addFormField("success_action_status", "201");
multipartv1.addFormField("x-goog-meta-programname", this.current_program_name);
multipartv1.addFormField("x-goog-meta-membername", this.member_element_id);
multipartv1.addFormField("x-goog-meta-tag1", tag1);
multipartv1.addFormField("x-goog-meta-tag2", tag2);
multipartv1.addFormField("x-goog-meta-tag3", tag3);
multipartv1.addFormField("x-goog-meta-tag4", tag4);
multipartv1.addFormField("x-goog-meta-tag5", tag5);
multipartv1.addFormField("policy", this.policy);
multipartv1.addFormField("signature", this.signature);
multipartv1.addFilePart("file", new File(this.file_absolute_path));
List<String> response_multipart = multipartv1.finish();
Log.e(Tag, "SERVER REPLIED:");
for (String line : response_multipart) {
Log.e(Tag, "Upload Files Response:::" + line);
}
The "policy" is generated from my backend (Google App Engine) using Google Cloud Endpoint API. This is as policy document supported by Google Cloud Storage XML API as listed here. The "policy" works perfectly when accessed through a Webapplication.
The "policy" looks like this -
ewkJCQoJCQkJImV4cGlyYXRpb24iOiAiMjAxNi0wNi0xNlQxMToxMToxMVoiLAoJCQkJImNvbmRpdGlvbnMiOiBbCgkJCQkJWyJzdGFydHMtd2l0aCIsICIka2V5IiwgIiIgXSwKCQkJCQl7ImFjbCI6ICJidWNrZXQtb3duZXItcmVhZCIgfSwKCQkJCQl7ImJ1Y2tldCI6ICJlbmdhZ2VkLXBhcnNlYy02MTIuYXBwc3BvdC5jb20ifSwKCQkJCQl7InN1Y2Nlc3NfYWN0aW9uX3JlZGlyZWN0Ijogc3VjY2Vzc19yZWRpcmVjdCB9LAoJCQkJCXsic3VjY2Vzc19hY3Rpb25fc3RhdHVzIjogIjIwMSJ9LAkJCQoJCQkJCVsiZXEiLCAiJENvbnRlbnQtVHlwZSIsICJpbWFnZS9qcGVnIiBdLAoJCQkJCVsic3RhcnRzLXdpdGgiLCAiJHgtZ29vZy1tZXRhLXByb2dyYW1uYW1lIiwgIiJdLAoJCQkJCVsic3RhcnRzLXdpdGgiLCAiJHgtZ29vZy1tZXRhLW1lbWJlcm5hbWUiLCAiIl0sCgkJCQkJWyJzdGFydHMtd2l0aCIsICIkeC1nb29nLW1ldGEtdGFnMSIsICIiXSwKCQkJCQlbInN0YXJ0cy13aXRoIiwgIiR4LWdvb2ctbWV0YS10YWcyIiwgIiJdLAoJCQkJCVsic3RhcnRzLXdpdGgiLCAiJHgtZ29vZy1tZXRhLXRhZzMiLCAiIl0sCgkJCQkJWyJzdGFydHMtd2l0aCIsICIkeC1nb29nLW1ldGEtdGFnNCIsICIiXSwKCQkJCQlbInN0YXJ0cy13aXRoIiwgIiR4LWdvb2ctbWV0YS10YWc1IiwgIiJdLAoJCQkJCVsiY29udGVudC1sZW5ndGgtcmFuZ2UiLCAwLCAzMDAwMDAwMF0KCQkJCQldCQkJCQoJCQkJfQ==
My fear is when I add the parameter for "policy" in my HttpURLConnection, something is messed up. The code to add the "policy" parameter is this -
public void addFormField(String name, String value) {
writer.append("--" + boundary).append(LINE_FEED);
writer.append("Content-Disposition: form-data; name=\"" + name + "\"")
.append(LINE_FEED);
writer.append("Content-Type: text/plain; charset=" + charset).append(
LINE_FEED);
writer.append(LINE_FEED);
writer.append(value).append(LINE_FEED);
writer.flush();
}
The HTTP Post call is here -
public List<String> finish() throws IOException {
List<String> response = new ArrayList<String>();
writer.append(LINE_FEED).flush();
writer.append("--" + boundary + "--").append(LINE_FEED);
writer.close();
// checks server's status code first
int status = httpConn.getResponseCode();
if (status == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(
httpConn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
response.add(line);
}
reader.close();
httpConn.disconnect();
} else {
throw new IOException("Server returned non-OK status: " + status);
}
return response;
}
The boundary string is this
String boundary = "===" + System.currentTimeMillis() + "===";

How would I receive all fields from a dynamic form with Struts?

I found myself with the following problem:
I have a page generated with logic:iterate that shows the current supervisor and assistant of a service.
That page also acts as a form where people can add their possible substitutes, but you never know how many of those are there.
Due to the environment I am currently working with it had to be without JSTL so a lot of options were gone; couldn't get DynaActionForm working for this either.
Since I couldn't find anything but I already got the answer I decided to create this to answer anyone who might have the same issue.
Code:
public ActionForward post(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
String[] tot;
try {
Enumeration<?> fieldsForm = request.getParameterNames();
while(fieldsForm.hasMoreElements()) {
String current = (String) fieldsForm.nextElement();
tot = request.getParameterValues(current);
System.out.println("Field name is: " + current);
for (i=0; i<tot.length; i++) {
// do whatever you need to do; contents are in tot[i]
System.out.println("Value " + i + " is: " + tot[i]);
}
}
catch (Exception ex) {
ex.printStackTrace();
System.err.println(ex.getMessage());
}
}

REST Application - I don't receive the error from server in case of insucess - the output displays only if the request is successfull

I have the next problem: I've made a simple application which retrieves information from a server (GET Method). The application works fine as long as the information is retrieved successfully.
In case of insuccess, I don't receive the error from the server (ex: 401 - Unauthorized, 403 - Forbidden - when the authentication token is incorrect for example).
How can I fix this so that my application will return the error from server ? I've done also a POST method and there it's working, I received all erorrs froem server in case of insuccess.
What i'm doing wrong with this code ? Why i don't receive an error in case of insuccess?
The only error I receive in output is 400 in all scenarios and this isn't enough.
For example, if the authorization token is incorrect, I should receive from server 401 - Unauthorized. I know this because i'm doing test with other REST application (like POSTMAN). Can it be fixed to show the errors related to that scenarios ?
void example2() {
// GET METHOD !
try {
String webPage = "https://www.clients.ro";
String name = "user";
String password = "pass";
String authString = name + ":" + password;
System.out.println("Decoded authorization token" + authString);
//byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
//String authStringEnc = new String(authEncBytes);
byte[] authEncBytes = authString.getBytes(StandardCharsets.UTF_8);
String authStringEnc = DatatypeConverter.printBase64Binary(authEncBytes);
System.out.println("Token encoded in Base64 " + authStringEnc);
URL url = new URL(webPage);
URLConnection urlConnection = url.openConnection();
urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);
InputStream is = urlConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
int numCharsRead;
char[] charArray = new char[1024];
StringBuffer sb = new StringBuffer();
while ((numCharsRead = isr.read(charArray)) > 0) {
sb.append(charArray, 0, numCharsRead);
}
String result = sb.toString();
System.out.println(result);
System.out.println();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

Service Unavailable 503 Error during File Transfer with Openfire using Smack

I am trying to send a file through chat using openfire on the server and the smack java library.
This is the output I get:
Status :: Error Error :: null Exception :: service-unavailable(503) Is
it done? true
Here are my sender and receiver functions:
public void fileTransfer(String fileName, String destination) throws XMPPException {
// Create the file transfer manager
FileTransferManager manager = new FileTransferManager(connection);
FileTransferNegotiator.setServiceEnabled(connection,true);
// Create the outgoing file transfer
OutgoingFileTransfer transfer = manager.createOutgoingFileTransfer(destination);
// Send the file
transfer.sendFile(new File(fileName), "You won't believe this!");
try {
Thread.sleep(10000);
}
catch(Exception e){}
System.out.println("Status :: " + transfer.getStatus() + " Error :: " + transfer.getError() + " Exception :: " + transfer.getException());
System.out.println("Is it done? " + transfer.isDone());
}
public void fileReceiver(final boolean accept, final String fileName) {
// Create the file transfer manager
final FileTransferManager manager = new FileTransferManager(connection);
// Create the listener
manager.addFileTransferListener(new FileTransferListener() {
public void fileTransferRequest(FileTransferRequest request) {
// broadcast something here. Wheather users want to accept file
// Check to see if the request should be accepted
if(accept) {
// Accept it
IncomingFileTransfer transfer = request.accept();
try {
transfer.recieveFile(new File(fileName));
System.out.println("File " + fileName + "Received Successfully");
//InputStream input = transfer.recieveFile();
} catch (XMPPException ex) {
Logger.getLogger(XmppManager.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
// Reject it
request.reject();
}
}
});
}
I had same problem, I investigated the stanza and solved it this way.
Many people use "/Smack" or "/Resource" as resource part in jid, but that can be done another way.
Resource path is changing with every presence changed of user. Lets say we want to send image to this user:
"user1#mydomain"
You must add "/Resource" part to this jid and it become this:
user1#mydomain/Resource
But /Resource path is changing with presence so you must follow every presence change to update resource path.
Best way is to get user presence is in roster listener and in presencheChanged() method you get last user resource part like this:
Roster roster=getRoster();
roster.addRosterListener(new RosterListener() {
#Override
public void entriesAdded(Collection<Jid> addresses) {
Log.d("entriesAdded", "ug");
context.sendBroadcast(new Intent("ENTRIES_ADDED"));
}
#Override
public void entriesUpdated(Collection<Jid> addresses) {
Log.d("entriesUpdated", "ug");
}
#Override
public void entriesDeleted(Collection<Jid> addresses) {
Log.d("entriesDeleted", "ug");
}
#Override
public void presenceChanged(Presence presence) {
Log.d("presenceChanged", "ug");
//Resource from presence
String resource = presence.getFrom().getResourceOrEmpty().toString();
//Update resource part for user in DB or preferences
//...
}
});
}
Resource string will be some generated string like "6u1613j3kv" and jid will become:
user1#mydomain/6u1613j3kv
That means that you must create your outgoing transfer like this:
EntityFullJid jid = JidCreate.entityFullFrom("user1#mydomain/6u1613j3kv");
OutgoingFileTransfer transfer = manager.createOutgoingFileTransfer(jid)
transfer.sendFile(new File("DirectoryPath"), "Description");
And that is how i have solved my problem with file transfer on smack and Openfire.
In your case jid is destination.
Also to mention you must add following properties in your Openfire server:
xmpp.proxy.enabled - true
xmpp.proxy.externalip - MY_IP_ADDRESS
xmpp.proxy.port - 7777
Just to mention, I am using Openfire 4.0.2 and Smack 4.2.2.
Also this can be configured the easy way, just set the resource on
XMPPTCPConnectionConfiguration.Builder .
like
XMPPTCPConnectionConfiguration.Builder configurationBuilder =
XMPPTCPConnectionConfiguration.builder();
configurationBuilder.setResource("yourResourceName");