I have problem with ArrayList mailing again. Program building and working succesfully about 1 month. But today i detect some important mails not coming from my program. And I begin debugging my code. Let me share my findings.
I have a Arraylist populated from some DB queries;
ArrayList<String> importantlist = new ArrayList<String>();
When populating complete I send this Arraylist to Mail sender method;
if (importantlist.size() > 0) {
sendMail(importantlist);
}
sendMail method;
public void sendMail(ArrayList cominglist) throws Exception {
StringBuilder b = new StringBuilder();
for(Object coming: cominglist)
b.append(coming).append("\n");
String cominglistString = b.toString();
Email email = new SimpleEmail();
email.setHostName("hostname here");
email.setSmtpPort(587);
email.setAuthentication("mail sender user here","userpasswordhere");
email.setSSLOnConnect(false);
email.setFrom("mail sender address here");
email.setSubject("Example important list");
email.setMsg("Example important List body;\n"+cominglistString);
email.addTo("receiver user here");
email.addTo("receiver user here");
email.send();
System.out.println("success");
}
When I debug this method I see message is null when cursor come to email.send(); But this program work succesfully and send lists to users about 1 month.
If I try another sendMail method just like below, mails succesfully coming to my mailbox;
public void sendMail2() throws Exception {
Email email = new SimpleEmail();
email.setHostName("hostname here");
email.setSmtpPort(587);
email.setAuthentication("mail sender user here","userpasswordhere");
email.setSSLOnConnect(false);
email.setFrom("mail sender address here");
email.setSubject("Example simple mail");
email.setMsg("Example simple mail body;\n");
email.addTo("receiver user here");
email.addTo("receiver user here");
email.send();
System.out.println("success");
}
---Edit---
email.setMsg("Example important List body;\n"+cominglistString); line edited.
And yes, my list is bigger than 0 I am sure.
Any idea?
---Edit 2---
Really i am shocked now!! I continue debugging and mail come to my mailbox this time when i debugging. Because i see cominglistString and email message box populated this time. Mails dont came sometimes. I am stuck :(
Problem Solved. It was a local Firewall problem. Firewall block communication between Application Machine and Mail Server.
Firewall restarted and problem is gone.
Thanks for all answers.
Related
I work on university project in java. I have to download attachments from new emails using GMAIL API.
I successfully connected to gmail account using OAuth 2.0 authorization.
private static final List<String> SCOPES = Collections.singletonList(GmailScopes.GMAIL_READONLY);
I tried to get unseen mails using
ListMessagesResponse listMessageResponse = service.users().messages().list(user).setQ("is:unseen").execute();
listMessageResponse is not null but when I call method .getResultSizeEstimate() it returns 0
also I tried to convert listMessageResponse to List < Message > (I guess this is more usable) using
List<Message> list = listMessageResponse.getMessages();
But list launches NullPointerException
Then tried to get each attachment with
for(Message m : list) {
List<MessagePart> part = m.getPayload().getParts();
for(MessagePart p: part) {
if(p.getFilename()!=null && p.getFilename().length()>0) {
System.out.println(p.getFilename()); // Just to check attachment filename
}
}
}
Is my approach correct (if not how to fix it) and how should I download those attachments.
EDIT 1:
Fixed q parameter, I mistakenly wrote is:unseen instead of is:unread.
Now app reaches unread mails successfully.
(For example there was two unread mails and both successfully reached, I can get theirs IDs easy).
Now this part trows NullPointerException
List<MessagePart> part = m.getPayload().getParts();
Both messages have attachments and m is not null (I get ID with .getID())
Any ideas how to overcome this and download attachment?
EDIT 2:
Attachments Downloading part
for(MessagePart p : parts) {
if ((p.getFilename() != null && p.getFilename().length() > 0)) {
String filename = p.getFilename();
String attId = p.getBody().getAttachmentId();
MessagePartBody attachPart;
FileOutputStream fileOutFile = null;
try {
attachPart = service.users().messages().attachments().get("me", p.getPartId(), attId).execute();
byte[] fileByteArray = Base64.decodeBase64(attachPart.getData());
fileOutFile = new FileOutputStream(filename); // Or any other dir
fileOutFile.write(fileByteArray);
fileOutFile.close();
}catch (IOException e) {
System.out.println("IO Exception processing attachment: " + filename);
} finally {
if (fileOutFile != null) {
try {
fileOutFile.close();
} catch (IOException e) {
// probably doesn't matter
}
}
}
}
}
Downloading working like charm, tested app with different type of emails.
Only thing left is to change label of unread message (that was reached by app) to read. Any tips how to do it?
And one tiny question:
I want this app to fetch mails on every 10 minutes using TimerTask abstract class. Is there need for manual "closing" of connection with gmail or that's done automatically after run() method iteration ends?
#Override
public void run(){
// Some fancy code
service.close(); // Something like that if even exists
}
I don't think ListMessagesResponse ever becomes null. Even if there are no messages that match your query, at least resultSizeEstimate will get populated in the resulting response: see Users.messages: list > Response.
I think you are using the correct approach, just that there is no message that matches your query. Actually, I never saw is:unseen before. Did you mean is:unread instead?
Update:
When using Users.messages: list only the id and the threadId of each message is populated, so you cannot access the message payload. In order to get the full message resource, you have to use Users.messages: get instead, as you can see in the referenced link:
Note that each message resource contains only an id and a threadId. Additional message details can be fetched using the messages.get method.
So in this case, after getting the list of messages, you have to iterate through the list, and do the following for each message in the list:
Get the message id via m.getId().
Once you have retrieved the message id, use it to call Gmail.Users.Messages.Get and get the full message resource. The retrieved message should have all fields populated, including payload, and you should be able to access the corresponding attachments.
Code sample:
List<Message> list = listMessageResponse.getMessages();
for(Message m : list) {
Message message = service.users().messages().get(user, m.getId()).execute();
List<MessagePart> part = message.getPayload().getParts();
// Rest of code
}
Reference:
Class ListMessagesResponse
Users.messages: list > Response
I'm using smack-android:4.1.4 to connect to xmpp server, and I use this code to connect to a multi user chat room on that server:
MultiUserChatManager mucManager = MultiUserChatManager.getInstanceFor(connection);
MultiUserChat muc = mucManager.getMultiUserChat(roomName);
muc.join(nickName,password,discussionHistory,timeout);
In this room if I'm an owner then I can kick or ban a user, to ban a user:
muc.banUser(userJID, reason);
and I can get the banned users list in this room:
List<Affiliate> bannedList = muc.getOutcasts();
QUESTION 1: how can I unban a user from the previous list?
the problem is I couldn't find any function like:
//muc.unbanUser(String userJID); // there's nothing close to this
I read the whole documentation but came to nothing, so what am I missing here?
I can get the jid of any banned user through the outcasts list:
String jid = outcast.getJid(); // where outcast is of type Affiliate
but no function to use this jid to unban the user.
Question 2: this question is related to rooms but not to the banned list issue, in some rooms I get the following exception:
PacketParserUtils? Failed to parse extension packet in Presence packet. Attributes: from=roomName#conference.myXmppServer/someUserNickName id=null
org.jivesoftware.smack.SmackException: Caps elment with missing attributes. Attributes: hash=null version=1.0.0.84 node=http://www.google.com/xmpp/client/caps
at org.jivesoftware.smackx.caps.provider.CapsExtensionProvider.parse(CapsExtensionProvider.java:54)
at org.jivesoftware.smackx.caps.provider.CapsExtensionProvider.parse(CapsExtensionProvider.java:28)
at org.jivesoftware.smack.provider.Provider.parse(Provider.java:35)
at org.jivesoftware.smack.util.PacketParserUtils.parseExtensionElement(PacketParserUtils.java:929)
at org.jivesoftware.smack.util.PacketParserUtils.addExtensionElement(PacketParserUtils.java:1060)
at org.jivesoftware.smack.util.PacketParserUtils.parsePresence(PacketParserUtils.java:583)
at org.jivesoftware.smack.util.PacketParserUtils.parseStanza(PacketParserUtils.java:155)
at org.jivesoftware.smack.AbstractXMPPConnection.parseAndProcessStanza(AbstractXMPPConnection.java:956)
at org.jivesoftware.smack.tcp.XMPPTCPConnection.access$500(XMPPTCPConnection.java:140)
at org.jivesoftware.smack.tcp.XMPPTCPConnection$PacketReader.parsePackets(XMPPTCPConnection.java:989)
at org.jivesoftware.smack.tcp.XMPPTCPConnection$PacketReader.access$300(XMPPTCPConnection.java:944)
at org.jivesoftware.smack.tcp.XMPPTCPConnection$PacketReader$1.run(XMPPTCPConnection.java:959)
at java.lang.Thread.run(Thread.java:856)
and it refers to some code inside the smack library classes, so it's not some uncaught exception inside my code,
what is the cause of this exception? and isn't there a way to handle such unparsed data?
I'm using ParsingExceptionCallback in other part of my application:
connection.setParsingExceptionCallback( parsingExceptionCallback );
but this function is not called for this case, is there any similar functions for MultiUserChat class ?
maybe making a user member will remove the jid from banned list? because according to xmpp a jid can not be in more than one list... how ever there are five lists in xmpp, one for owners,admins,members, none and banned.
at the following website
http://xmpp.org/extensions/xep-0045.html
read
4.1 General Terms
5.2.1 Privileges
optional read
Admin Use Cases
i'm using ejabberd server with smack-android-4.1.9 library and below code work perfect for me.
//remove the user from Group of ejabberd.
//revoke the Ownership,Admin and membership from group of ejabberd.
public void removeUser(String room_jid,RosterVO removeUserRosterVo,boolean isAdmin){
MultiUserChatManager multichatmanager = MultiUserChatManager.getInstanceFor(connection);
MultiUserChat chatRoom = multichatmanager.getMultiUserChat(room_jid);
try {
if (isAdmin) {
chatRoom.revokeOwnership(removeUserRosterVo.getJid());
chatRoom.revokeAdmin(removeUserRosterVo.getJid());
chatRoom.revokeMembership(removeUserRosterVo.getJid());
} else {
chatRoom.revokeMembership(removeUserRosterVo.getJid());
}
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
} catch (XMPPException.XMPPErrorException e) {
e.printStackTrace();
} catch (SmackException.NoResponseException e) {
e.printStackTrace();
}
}
Suppose i have a mail in my lotus notes,Now i have to get from which IP address that mail is sent.How do i get the IP address in domino designer through java.Is there any header information from which i can get the IP Address.
I tried looking in the properties of the document but i could not find anything in there apart from which server i got the mails Please help.
A Notes mail document has an item "Received" which contains information from every server it has passed. You can't find out client's IP address this way (I think that's impossible) but you get the server's IP address at least.
It is not that easy to get ip address from item "Received" though because there are several items "Received" and with document's methods you always get only the last created. As a workaround you have to read item and remove item in a cycle so that you get all items "Received". Here is the Java code for getting the ip address closest to sender:
private String getIPSender(Document doc) {
String ip = "";
if (doc != null) {
try {
while (doc.hasItem("Received")) {
Item item = doc.getFirstItem("Received");
if (item.getValueString().contains("[")) {
ip = item.getValueString();
}
item.remove();
}
if (!ip.isEmpty()) {
ip = ip.substring(ip.indexOf("[") + 1);
ip = ip.substring(0, ip.indexOf("]"));
}
} catch (Exception e) {
ip = "";
}
}
return ip;
}
I'm sending a mail using JavaMail from inside a JSP page as follows:
String from= request.getParameter("from");
String to= request.getParameter("to");
String thanks= request.getParameter("thanks");
String subject= request.getParameter("subject");
try{
SmtpClient client = new SmtpClient("smtp.example.com");
client.from(from);
client.to(to);
PrintStream message = client.startMessage();
message.println("From: " + from);
message.println("To: " + to);
message.println("Subject: " + subject);
message.println();
Enumeration paramNames = request.getParameterNames();
while(paramNames.hasMoreElements()) {
String paramName = (String) paramNames.nextElement();
String paramValue = request.getParameter(paramName);
if (request.getParameter(paramName) != null &&
request.getParameter(paramName) != "") {
message.println(paramName + ": " + paramValue);
message.println();
}
}
client.closeServer();
}
catch (IOException e){
System.out.println("ERROR IN DELIVERING THE FORM:"+e);
}
This was working fine first and sent the data to my Inbox, but after many trials and insignificant changes, now the post goes to my Spam folder.
I appreciate if anyone could tell me where the problem is and what causes this.
Mail goes to spam when Google find any insecure IP or links, Make sure you don't have any other IP which is not authenticated (can be access by https://"IP")
What causes this? Your spam filter!
Depending on what you/your mail provider uses as spam filter, you might learn something from the mail headers - I recall spamassassin giving some information about what filter scored how high, and the resulting spam score. Others might do that as well.
You might also be able to train your spam filter to recognize this mail as non-spam (ham) if you remove it from the spamfolder.
If there is overflow emailId then most of the times it goes to spam, It's done by google. But you can still change that protocol by google by below method:
First time you need to go to your spam and open the mail then the cross option would be above the mail (Which means cancel that mail from spam) click on that (mentioned in the screenshot:.
From the next time, it would not go to your spam.
I have a requirement where I need to send SMS from my Web Application to any Mobile in India .
I got below code from a ipipi.com website:
I want to implement this functionality, could anybody please help me what values are to be provided here:
String username = "YoureIPIPIUsername";
String password = "YourPassword";
String smtphost = "ipipi.com";
String compression = "Compression Option goes here - find out more";
String from = "YoureIPIPIUsername#ipipi.com";
String to = "DestinationPhoneNumber#sms.ipipi.com";
String body = "Your Message";
SMTPSend.class
import java.io.*;
import java.net.InetAddress;
import java.util.Properties;
import java.util.Date;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SMTPSend {
public SMTPSend() {
}
public void msgsend() {
String username = "YoureIPIPIUsername";
String password = "YourPassword";
String smtphost = "ipipi.com";
String compression = "Compression Option goes here - find out more";
String from = "YoureIPIPIUsername#ipipi.com";
String to = "DestinationPhoneNumber#sms.ipipi.com";
String body = "Your Message";
Transport tr = null;
try {
Properties props = System.getProperties();
props.put("mail.smtp.auth", "true");
// Get a Session object
Session mailSession = Session.getDefaultInstance(props, null);
// construct the message
Message msg = new MimeMessage(mailSession);
//Set message attributes
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = {new InternetAddress(to)};
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject(compression);
msg.setText(body);
msg.setSentDate(new Date());
tr = mailSession.getTransport("smtp");
tr.connect(smtphost, username, password);
msg.saveChanges();
tr.sendMessage(msg, msg.getAllRecipients());
tr.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] argv) {
SMTPSend smtpSend = new SMTPSend();
smtpSend.msgsend();
}
}
If the code above is linking to a service that converts incoming Email messages to outgoing SMS messages, you presumably need to purchase credit as stated by Alex K.
A better way to send SMSes would be to use SMSLib to interface with a cellular provider's SMSC. You also then need to make sure that provider is able to route SMSes to all cellular networks.
Your question seems specific to some service provider/API. But I would like to give a generic answer here.
Sending SMS need a SMS gateway to a SMSC. There are two simple methods[of-cause more can be].
You can either use your SIM card[SMS enabled], or use someone else's SIM card. SIM card provides connection to a SMS gateway through your service provider with SMSC.
Either ways, sending SMS is not free.Others may say its LIKELY free, but at-least an advertisement or a long term business marketing strategy must be there.
The way you are continuing is using someone else's SIM through an API provided by them. Since those have dedicated bulk SMS accounts, it may faster, multiple threaded, service. They should commercially helpful to you to get your problem sorted.
If you want to send SMS from your SIM, you have to connect your SIM to computer and use an standard API to call SMS functionality. SMSLib is what I suggest. You need a hardware to connect your SIM to PC, either connect your mobile to it or, use a Data Modem[easy] and interface through a COM port.
Try this code here, if you want to try your own SMS gateway.
First create an account in ipipi.com and validate it by clicking the activation link sent to the mail.And give your username as YoureIPIPIUsername and password as YourPassword.
String smtphost = "ipipi.com"
String compression = "Compression Option goes here - find out more";
There are some compression types here if u don't want anything you can mention "None"
String from = "YoureIPIPIUsername#ipipi.com"
String to = "DestinationPhoneNumber#sms.ipipi.com";
Destination ph number should be +91 and the 10 digit number
String body = "Your Message";