Java Twitch IRC Bot - java

So I'm working on a basic Twitch Bot for my channel and the code is as follows:
Config.java
import java.io.IOException;
import org.jibble.pircbot.IrcException;
import org.jibble.pircbot.NickAlreadyInUseException;
public class Config {
private static final String OAUTH = "MYOAUTHHERE";
private static final String ADRESS = "irc.chat.twitch.tv.";
private static final int PORT = 6667;
private static final String channelName = "#MYCHANNELNAMEHERE";
public static void main(String[] args) throws NickAlreadyInUseException, IOException, IrcException {
TwitchBot bot = new TwitchBot();
bot.setVerbose(true);
bot.connect(ADRESS, PORT, OAUTH);
// bot.onMessage(channelName, "Bot", channelName, channelName, channelName);
System.out.println("Connected!");
bot.joinChannel(channelName);
System.out.println("Successfully joined channel!");
bot.sendMessage(channelName, "Hello, I am a bot");
}
}
TwitchBot.java
import org.jibble.pircbot.*;
public class TwitchBot extends PircBot {
private static final String channelName = "#MYCHANNELNAME";
private final String botName = "THEBOTNAME";
public TwitchBot() {
this.setName(botName);
this.setLogin(botName);
}
public String getchannelName() {
return channelName;
}
#Override
public void onMessage(String channel, String sender, String login, String hostname, String message) {
if (message.equalsIgnoreCase("time")) {
String time = new java.util.Date().toString();
sendMessage(channel, sender + ": The time is now " + time);
}
}
}
The console displays "Connected!" and "Successfully joined channel" however the bot is unresponsive, and is not in the channel I specified. It also does not print "Hello I am a bot" in the chat.

There are few things to consider about Twitch.
Your email must be validated. Settings -> Profile -> Profile Settings
Channel names must be entered as lowercase.
Nickname are useless, twitch are using your profile nickname.
Twitch uses IRCv3 Client Capability Negotiation aka CAP, which means you should be use it as well.
You should only try enter existing channels, otherwise the server will ignore your JOIN channel.
Twitch, allow themselves the opportunity to change your nickname while you logged in, which means, that the expected nick results, provided by TwitchBot class, can, and probably be incorrect if you supply any name different from your logged in profile nickname.
Twitch IRC Capabilities, can be found Here, here are few..
membership: JOIN, MODE, NAMES, PART
tags: PRIVMSG, etc'
You should add those CAP, first thing you are logged in.
Important Notice: PIRCBot, doesn't look to support twitch PRIVMSG format, which means onMessage callback, will not be called. which leaves you to handle the parsing of received messages, through handleLine general callback.
Code as been updated to apply to above changes, and you should set the final variables in order it to work.
TwitchBot.java
import org.jibble.pircbot.*;
public class TwitchBot extends PircBot {
private final String requestedNick;
private String realNick;
private String realServer;
public TwitchBot(String nick) {
this.requestedNick = nick;
setName(this.requestedNick);
setLogin(this.requestedNick);
}
#Override
protected void onConnect() {
super.onConnect();
System.out.println("Connected!");
// Sending special capabilities.
sendRawLine("CAP REQ :twitch.tv/membership");
sendRawLine("CAP REQ :twitch.tv/commands");
sendRawLine("CAP REQ :twitch.tv/tags");
}
#Override
protected void handleLine(String line) {
super.handleLine(line);
if (line.startsWith(":")) {
String[] recvLines = line.split(" ");
// First message is 001, extract logged in information.
if (recvLines[1].equals("001")) {
this.realServer = recvLines[0].substring(1);
this.realNick = recvLines[2];
System.out.println("realServer: " + this.realServer);
System.out.println("realNick: " + this.realNick);
}
}
}
#Override
protected void onJoin(String channel, String sender, String login, String hostname) {
super.onJoin(channel, sender, login, hostname);
if (sender.equals(this.realNick)){
System.out.println("Successfully joined: " + channel);
}
}
#Override
protected void onMessage(String channel, String sender, String login, String hostname, String message) {
if (message.equalsIgnoreCase("time")) {
String time = new java.util.Date().toString();
sendMessage(channel, sender + ": The time is now " + time);
}
}
}
goFile.java
import java.io.IOException;
import org.jibble.pircbot.IrcException;
import org.jibble.pircbot.NickAlreadyInUseException;
public class goFile {
private static final String OAUTH = "MYOAUTHHERE";
private static final String ADDRESS = "irc.twitch.tv.";
private static final int PORT = 6667;
private static final String Nick = "MYNICKHERE";
private static final String Channel = "#MYCHANNELHERE";
public static void main(String[] args) throws NickAlreadyInUseException, IOException, IrcException {
TwitchBot bot = new TwitchBot(Nick);
bot.setVerbose(true);
bot.connect(ADDRESS, PORT, OAUTH);
bot.joinChannel(Channel);
bot.sendMessage(Channel, "Hello, I am a bot");
}
}

Related

Javalin Websocket Client silently fails to connect

I'm trying to create a Websocket client that talks to a Websocket server. My server code seems to run ok as I can connect to it using a web based client. But my Java implementation just fails silently to connect, then throws an exception on send().
This is my scratch rig for trying this out:
UPDATE:
I found the problem was the example code was using a deprecated version of DRAFT. I updated and can now get the two threads to talk to each other. I've updated the code to show the working version.
One question I have now is how do I shut down the server?
package com.github.museadmin.api;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.handshake.ServerHandshake;
import java.net.URI;
import java.net.URISyntaxException;
public class WsThreadRig {
private static final String threadName = "ism_thread";
public static void main(String[] args) throws InterruptedException, URISyntaxException {
ISMWebSocket server = new ISMWebSocket.Builder()
.port(7000)
.uri("/websocket")
.identity("server")
.host("localhost")
.build();
Thread thread = new Thread (server, threadName);
thread.start ();
Thread.sleep(1000L);
WebSocketClient mWs = new WebSocketClient(
new URI( "ws://127.0.0.1:7000/websocket" ),
new Draft_6455()
)
{
#Override
public void onMessage( String message ) {
System.out.println(
String.format("Message received from server (%s)",
message)
);
}
#Override
public void onOpen( ServerHandshake handshake ) {
System.out.println( "Client opened connection" );
}
#Override
public void onClose( int code, String reason, boolean remote ) {
System.out.println(
String.format("Client closed connection because (%s)", reason)
);
}
#Override
public void onError( Exception ex ) {
ex.printStackTrace();
}
};
//open websocket
mWs.connectBlocking();
Thread.sleep(1000L);
String message = "Test message from client";
//send message
mWs.send(message);
mWs.close();
}
}
I'll include the Websocket builder code below but as I said, I can connect to it ok on ws://localhost:7000/websocket using https://websocketking.com/ when I run main and am sitting in the loop with the server running in the background thread.
package com.github.museadmin.api;
import io.javalin.Javalin;
import java.util.Optional;
public class ISMWebSocket implements Runnable {
private Integer port;
private String uri;
private String identity;
private String host;
private ISMWebSocket(Builder builder) {
this.port = builder.port;
this.uri = builder.uri;
this.identity = builder.identity;
}
#Override
public void run() {
Javalin app = Javalin.create().start(this.host, this.port);
app.ws(this.uri, ws -> {
ws.onConnect(ctx -> {
System.out.println("Client connected to server");
ctx.send("Test message from server");
}
);
ws.onClose(ctx -> {
System.out.println("Client disconnected from server");
}
);
ws.onMessage(ctx -> System.out.println(
String.format("Message received from client (%s)", ctx.message())
)
);
ws.onError(ctx -> {
System.out.println(
String.format("ERROR: (%s)", ctx.error().getMessage())
);
});
});
}
public Optional<Integer> getPort() {
return Optional.ofNullable(port);
}
public Optional<String> getUri() {
return Optional.ofNullable(uri);
}
public Optional<String> getIdentity() {
return Optional.ofNullable(identity);
}
public Optional<String> getHost() {
return Optional.ofNullable(host);
}
public static class Builder {
private Integer port;
private String uri;
private String identity;
private String host;
public Builder port(Integer port) {
this.port = port;
return this;
}
public Builder uri(String uri) {
this.uri = uri;
return this;
}
public Builder identity(String identity) {
this.identity = identity;
return this;
}
public Builder host(String host) {
this.host = host;
return this;
}
public Builder fromPrototype(ISMWebSocket prototype) {
port = prototype.port;
uri = prototype.uri;
identity = prototype.identity;
host = prototype.host;
return this;
}
public ISMWebSocket build() {
return new ISMWebSocket(this);
}
}
}
This is the output:
Client opened connection
Client connected to server
Message received from server (Test message from server)
Message received from client (Test message from client)
Client disconnected from server
Client closed connection because ()
Brad
PS:
I changed the connection to a blocking connection and added a print out of the reason in the onClose() method for the client which now reports:
org.java_websocket.drafts.Draft_10#2025740c refuses handshake
I don't know what the drafts library is doing to be honest, so will read up on that next.
So the DRAFT_10 reference was deprecated. Updated it to the latest release
WebSocketClient mWs = new WebSocketClient(
new URI( "ws://127.0.0.1:7000/websocket" ),
new Draft_6455()
)

aws ses java Invalid date

when I use aws ses to send a email exception happened which show me that
com.amazonaws.AmazonServiceException:
Invalid date Mon, 14 Dec 2015 02:08:56 +00:00. It must be in one of
the formats specified by HTTP RFC 2616 section 3.3.1 (Service:
AmazonSimpleEmailService; Status Code: 400; Error Code:
InvalidParameterValue; Request ID:
e2716096-a207-11e5-9615-8135b4d7f5f9)
follows is my code :
public class SESEmailUtil {
private final String accesskey = "XXXXXXXXX";
private final String secretkey = "XXXXXXXXXXXXXXXX";
private String REGION = "us-east-1";
private Region region;
private static AWSCredentials credentials;
private static AmazonSimpleEmailServiceClient sesClient;
private static SESEmailUtil sesEmailUtil = null;
private SESEmailUtil() {
init(accesskey, secretkey);
};
public void init(String accesskey, String secretkey) {
credentials = new BasicAWSCredentials(accesskey, secretkey);
sesClient = new AmazonSimpleEmailServiceClient(credentials);
region = Region.getRegion(Regions.fromName(REGION));
sesClient.setRegion(region);
}
public static SESEmailUtil getInstance() {
if (sesEmailUtil == null) {
synchronized (SESEmailUtil.class) {
return new SESEmailUtil();
}
} else {
return sesEmailUtil;
}
}
public void sendEmail(String sender, LinkedList<String> recipients,
String subject, String body) {
Destination destination = new Destination(recipients);
try {
Content subjectContent = new Content(subject);
Content bodyContent = new Content(body);
Body msgBody = new Body(bodyContent);
Message msg = new Message(subjectContent, msgBody);
SendEmailRequest request = new SendEmailRequest(sender,
destination, msg);
SendEmailResult result = sesClient.sendEmail(request);
System.out.println(result + "Email sent");
} catch (Exception e) {
e.printStackTrace();
System.out
.println("Exception from EmailSender.java. Email not send");
}
}
}
public class TestSend {
private static String sender = "";
private static LinkedList<String> recipients = new LinkedList<String>();
static final String BODY = "This email was sent through Amazon SES by using the AWS SDK for Java.";
static final String SUBJECT = "Amazon SES test (AWS SDK for Java)";
public static void main(String args[]) {
SESEmailUtil sendUtil = SESEmailUtil.getInstance();
String receive = "qinwanghao#XXXX.com.cn";
recipients.add(receive);
sendUtil.sendEmail(sender, recipients, SUBJECT, BODY);
}
}
The code is based on the example provided by aws.
the date Mon, 14 Dec 2015 02:08:56 +00:00 is invalid , but where can I modify the format?
wish someone can help me.THK.
Issue is likely with Joda-time version. In case of this error you should check your dependency tree, with maven (mvn dependency:tree). Look for any joda-time versions conflicting with one supplied by aws-sdk. To fix: add the conflicting version of joda-time to exclusions in your pom.xml (or equivalent).

Java object LinkedList attribute: only receiving the first element on server-side using TCP

A little bit of context: the client is sending to the server a SOSPFPacket object (via TCP) that has various attributes, such as a Vector<LSA> lsaArray. The LSA itself has a LinkedList<LinkDescription> links attribute. In my test case, there are two messages being sent. In both messages, there is only one LSA in the vector. In the first message, the LSA has one LinkDescription, in the second, it has two. When I send a message, I increment the messageId.
The server receives both messages with proper ids, but in the second message, the links only contain one link instead of two. I'm clueless...
Here are the object implementations:
import java.io.*;
import java.util.Vector;
public class SOSPFPacket implements Serializable {
public final static short HELLO = 0;
public final static short LSU = 1;
public final static short OVER_BURDENED = 2;
public static int id = Integer.MIN_VALUE;
public String srcProcessIP;
public short srcProcessPort;
public String srcIP;
public String dstIP;
public short sospfType; //0 - HELLO, 1 - LinkState Update, 2 - Over Burdened
public String routerID;
public int messageId = id++;
public String neighborID; //neighbor's simulated IP address
public Vector<LSA> lsaArray = new Vector<>();
public String lsaInitiator = null;
}
import java.io.Serializable;
import java.util.LinkedList;
public class LSA implements Serializable {
public String linkStateID;
public int lsaSeqNumber = Integer.MIN_VALUE;
public LinkedList<LinkDescription> links = new LinkedList<LinkDescription>();
#Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append(linkStateID + ":").append(lsaSeqNumber + "\n");
for (LinkDescription ld : links) {
sb.append(ld);
}
sb.append("\n");
return sb.toString();
}
}
import java.io.Serializable;
public class LinkDescription implements Serializable {
public String linkID;
public int portNum;
public int tosMetrics;
public LinkDescription() {}
public LinkDescription(String linkID, int portNum, int tosMetrics) {
this.linkID = linkID;
this.portNum = portNum;
this.tosMetrics = tosMetrics;
}
public String toString() {
return linkID + "," + portNum + "," + tosMetrics;
}
}
To send the message, I do it via a Client.java thread implementing Runnable. Here are the relevant methods:
public void run() {
try {
_outputStream = new ObjectOutputStream(_clientSocket.getOutputStream());
sendMessage(SOSPFPacket.HELLO);
_inputStream = new ObjectInputStream(_clientSocket.getInputStream());
SOSPFPacket message = Util.receiveMessage(_inputStream);
if (message.sospfType == SOSPFPacket.OVER_BURDENED) {
System.out.println("Removing link with router " + message.srcIP + "...");
_router.removeLink(_remoteRouterIP);
return;
}
_remoteRouterDescription.setStatus(RouterStatus.TWO_WAY);
_router.addLinkDescriptionToDatabase(_remoteRouterDescription, _link.getWeight());
sendMessage(SOSPFPacket.HELLO);
message = Util.receiveMessage(_inputStream);
if (message.sospfType == SOSPFPacket.LSU) {
_router.synchronize(message.lsaArray);
}
_router.propagateSynchronization(message.lsaInitiator, message.srcIP);
} catch (IOException e) {
e.printStackTrace();
}
}
private void sendMessage(short messageType) {
try {
SOSPFPacket message = Util.makeMessage(_rd, _remoteRouterDescription, messageType, _router);
_outputStream.writeObject(message);
_outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
public class Util {
public static SOSPFPacket makeMessage(RouterDescription local, RouterDescription external, short messageType, Router rd) {
SOSPFPacket message = new SOSPFPacket();
message.srcProcessIP = local.getProcessIPAddress();
message.srcProcessPort = local.getProcessPortNumber();
message.srcIP = local.getSimulatedIPAddress();
message.dstIP = external.getSimulatedIPAddress();
message.sospfType = messageType;
message.routerID = local.getSimulatedIPAddress();
message.neighborID = external.getSimulatedIPAddress();
rd.getLsd().getStore().forEach((k, v) -> message.lsaArray.addElement(v));
message.lsaInitiator = messageType == SOSPFPacket.LSU ? message.srcIP : null;
return message;
}
public static SOSPFPacket receiveMessage(ObjectInputStream inputStream) {
SOSPFPacket receivedMessage = null;
try {
receivedMessage = (SOSPFPacket) inputStream.readObject();
String messageType;
switch (receivedMessage.sospfType) {
case SOSPFPacket.HELLO:
messageType = "HELLO";
break;
case SOSPFPacket.LSU:
messageType = "LINKSTATEUPDATE";
break;
case SOSPFPacket.OVER_BURDENED:
messageType = "OVER_BURDENED";
break;
default:
messageType = "UNKNOWN_STATE";
break;
}
System.out.println("received " + messageType + " from " + receivedMessage.srcIP + ";");
} catch (ClassNotFoundException e) {
System.out.println("No message received.");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return receivedMessage;
}
}
And the server instantiates a private ClientServiceThread when it receives a new connection, which is in charge of receiving the message.
private class ClientServiceThread implements Runnable {
Socket _clientSocket;
Thread _runner;
ClientServiceThread(Socket s) {
_clientSocket = s;
_runner = new Thread(this);
}
public Thread getRunner() { return _runner; }
public void run() {
ObjectInputStream inputStream = null;
ObjectOutputStream outputStream = null;
try {
inputStream = new ObjectInputStream(_clientSocket.getInputStream());
outputStream = new ObjectOutputStream(_clientSocket.getOutputStream());
while (true) {
try {
SOSPFPacket receivedMessage = Util.receiveMessage(inputStream);
//some logic not relevant since the receivedMessage is already not correct
}
}
}
}
}
Again, all SOSPFPacket fields are correctly received, except for the Vector<LSA> lsaArray...
Edit: I also tried sending a third sendMessage(SOSPFPacket.HELLO) after _router.propagateSynchronization(message.lsaInitiator, message.srcIP);. This time, the message being sent contains two LSA, the first one having two LinkDescription, the second one having one. Both LSA are received by the server, but still, only the first LinkDescription is received in the first LSA. The message id is correct in all three messages.
If I run everything a second time (i.e. I create a new Client and a new ClientService Thread for the already running routers), only then does the server finally receive two LinkDescription in the first LSA.
Java sends references to objects that have already been serialized, to preserve the integrity of object graphs.
You should call ObjectOutputStream.reset() after each writeObject().
Or use ObjectOutputStream.writeUnshared(), but note that it still shares referenced objects, i.e. if you try to send a list with both added and changed element objects, it will send the new list and new element objects, but not the element objects which have been changed.
Finally figured it out. Somehow it seems like the problem was the following line of code in Util.makeMessage: rd.getLsd().getStore().forEach((k, v) -> message.lsaArray.addElement(v));. I replaced it with rd.getLsd().getStore().forEach((k, v) -> message.lsaArray.add(new LSA(v))); with the following LSA constructor:
public LSA(LSA lsa) {
linkStateID = lsa.linkStateID;
lsaSeqNumber = lsa.lsaSeqNumber;
links = new LinkedList<>();
for (LinkDescription ld : lsa.links) {
LinkDescription linkD = new LinkDescription();
linkD.linkID = ld.linkID;
linkD.portNum = ld.portNum;
linkD.tosMetrics = ld.tosMetrics;
links.add(linkD);
}
}
In other words, I needed to deep copy the object contained in my message.

Cannot login into openfire account via XMPP

I have a very simple Java application that sends messages to an openfire server using a custom account called "thesis.dimfccs.sensors", who is seding a message to another custom account called "thesis.dimfccs".
I am using openfire 3.9.1 and my Java application is able to connect to the server, but it is unable to login into it. When I try to login, I get the following error:
Initializing connection to server localhost, port 5222, service gmail.com
Connected: true
Logging in: thesis.dimfccs.sensors, thesis.dimfccs.sensors.pwd
Exception in thread "main" No response from the server.:
at org.jivesoftware.smack.NonSASLAuthentication.authenticate(NonSASLAuthentication.java:73)
at org.jivesoftware.smack.SASLAuthentication.authenticate(SASLAuthentication.java:357)
at org.jivesoftware.smack.XMPPConnection.login(XMPPConnection.java:243)
at org.jivesoftware.smack.Connection.login(Connection.java:366)
at javacodegeeks.XmppManager.performLogin(XmppManager.java:76)
at javacodegeeks.XmppLocalTest.main(XmppLocalTest.java:44)
I know that the password and name for the test account are correct because I can enter the Spark IM client using them.
However, what really blows my mind, is that if I do the exact same thing using the "admin" account, everything works!
I have double checked the thesis.dimfccs.sensors password and gave it admin access, but it is still not enough.
Here is the code:
Main.java:
public class XmppLocalTest {
//Total number of messages sent during one minute.
public static final int MESSAGES_NUMBER = 120;
//Each message will have a random number between 0 and MAX_RANDOM.
public static final int MAX_RANDOM = 100;
private static final String SENDER_USERNAME = "thesis.dimfccs.sensors";
private static final String SENDER_PASSWORD = "thesis.dimfccs.sensors.pwd";
public static void main(String[] args) throws Exception {
String username = SENDER_USERNAME;
String password = SENDER_PASSWORD;
XmppManager xmppManager = new XmppManager("localhost", 5222,
"gmail.com");
xmppManager.init();
xmppManager.performLogin(username, password);
System.out.println("Login performed with success, setting status.");
xmppManager.setStatus(true, "Let the pain begin!");
System.out.println("Setting up receivers");
xmppManager.createEntry("thesis.dimfccs", "thesis.dimfccs");
//go message!
xmppManager.sendMessage("Hello world!", "thesis.dimfccs#gmail.com");
xmppManager.destroy();
}
}
XmppManager.java:
package javacodegeeks;
/**
* Main class with all the logic of the connection. Followed from the tutorials:
* http://www.javacodegeeks.com/2010/09/xmpp-im-with-smack-for-java.html
* */
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ChatManager;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.SmackConfiguration;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.Presence.Type;
public class XmppManager {
private static final int packetReplyTimeout = 500; // millis
private String server;
private int port;
private String service;
private ConnectionConfiguration config;
private XMPPConnection connection;
private ChatManager chatManager;
private MessageListener messageListener;
public XmppManager(String aServer, int aPort, String aService) {
server = aServer;
port = aPort;
service = aService;
}
public XmppManager(String server, int port) {
this(server, port, null);
}
public void init() throws XMPPException {
System.out.println(String.format("Initializing connection to server " + server + ", port " + port
+ ", service " + service));
SmackConfiguration.setPacketReplyTimeout(packetReplyTimeout);
if(service != null)
config = new ConnectionConfiguration(server, port, service);
else
config = new ConnectionConfiguration(server, port);
// config.setSASLAuthenticationEnabled(false);
// config.setSecurityMode(SecurityMode.disabled);
// SASLAuthentication.supportSASLMechanism("PLAIN", 0);
config.setSASLAuthenticationEnabled(true);
config.setSecurityMode(ConnectionConfiguration.SecurityMode.enabled);
connection = new XMPPConnection(config);
connection.connect();
System.out.println("Connected: " + connection.isConnected());
chatManager = connection.getChatManager();
messageListener = new MyMessageListener();
}
public void performLogin(String username, String password) throws XMPPException {
if (connection!=null && connection.isConnected()) {
System.out.println("Logging in: " + username + ", " + password);
connection.login(username, password);
}
}
public void setStatus(boolean available, String status) {
Presence.Type type = available? Type.available: Type.unavailable;
Presence presence = new Presence(type);
presence.setStatus(status);
connection.sendPacket(presence);
}
public void destroy() {
if (connection!=null && connection.isConnected()) {
connection.disconnect();
}
}
public void sendMessage(String message, String buddyJID) throws XMPPException {
System.out.println(String.format("Sending message " + message + " to user " + buddyJID));
Chat chat = chatManager.createChat(buddyJID, messageListener);
chat.sendMessage(message);
}
public void createEntry(String user, String name) throws Exception {
System.out.println(String.format("Creating entry for buddy " + user + " with name " + name));
Roster roster = connection.getRoster();
roster.createEntry(user, name, null);
}
private class MyMessageListener implements MessageListener {
#Override
public void processMessage(Chat chat, Message message) {
String from = message.getFrom();
String body = message.getBody();
System.out.println(String.format("Received message " + body + " from " + from));
}
}
}
What am I doing wrong? How can I fix this?
NOTE: If you believe this question is poor, please leave a comment and suggest an edit instead of down-voting it. This way I can actually improve the question and everyone gets happy!
The problem was that my server seemed to be inconsistent somehow. After deleting and re.creating the users, the problem got fixed !

how to send mail to a mailing list with java?

I want to send a mail to a mailing list every period of time (like every 40min or hour) with java on a unix server.
I'd like any code or tutorial to be able to do this.
Thanks
Sending a mail to a mailing list does not differ from sending a regular mail. The simplest way is to use commons-email. Check its examples.
JavaMail is the usual approach for this. You will need a SMTP-server for JavaMail to connect to.
String[] mailToId = {
"abc#mail.com",
"abc22#mail.com",
"abc33#mail.com"
};
for (int i = 0; i < mailToId.length; i++) {
message.addRecipient(Message.RecipientType.TO, new InternetAddress(mailToId[i]));;
}
In your java class you can use array of mail address and one by one mail address can call using for loop.
Within the for loop you can call
message.addRecipient();
method with array name.
look at the above example:
If it is not necessary to USE SMTP - java mail enough
Simple example
import java.util.Properties;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Message.RecipientType;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class MailSender {
private static String host = "";
private static String user = "";
private static String password = "";
private static int port = 465;
private static String from = "";
private static String to = "";
private static String auth = "true";
private static String debug = "false";
private static String socket_factory = "javax.net.ssl.SSLSocketFactory";
private static String subject = "";
private static String text = "";
/**
* Constructor. Fields - parameters for send mail.
*
* #param host - mail server.
* #param user - user
* #param password - login
* #param port - port
* #param from - mail from address
* #param to - mail to address
* #param subject - subject
* #param text - text of mail
*/
public MailSender(String host, String user, String password, int port,
String from, String to, String subject, String text) {
if (!host.isEmpty())
setHost(host);
if (!user.isEmpty())
setUser(user);
if (!password.isEmpty())
setPassword(password);
if (port == 0)
setPort(port);
if (!from.isEmpty())
setFrom(from);
if (!to.isEmpty())
setTo(to);
if (!subject.isEmpty())
setSubject(subject);
if (!text.isEmpty())
setText(text);
}
/**
* Send mail with parameters from constructor.
*/
public void send() {
// Use Properties object to set environment properties
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", getHost());
props.put("mail.smtp.port", getPort());
props.put("mail.smtp.user", getUser());
props.put("mail.smtp.auth", getAuth());
props.put("mail.smtp.starttls.enable","true");//for gmail?
props.put("mail.smtp.debug", getDebug());
props.put("mail.smtp.socketFactory.port", getPort());
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");//for gmail?
props.put("mail.smtp.socketFactory.fallback", "false");
try {
// Obtain the default mail session
Session session = Session.getDefaultInstance(props, null);
session.setDebug(new Boolean(getDebug()));
// Construct the mail message
MimeMessage message = new MimeMessage(session);
message.setText(getText());
message.setSubject(getSubject());
message.setFrom(new InternetAddress(getFrom()));
message
.addRecipient(RecipientType.TO,
new InternetAddress(getTo()));
message.saveChanges();
// Use Transport to deliver the message
Transport transport = session.getTransport("smtp");
transport.connect(getHost(), getUser(), getPassword());
transport.sendMessage(message, message.getAllRecipients());
transport.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static String getHost() {
return host;
}
public static void setHost(String host) {
MailSender.host = host;
}
public static String getUser() {
return user;
}
public static void setUser(String user) {
MailSender.user = user;
}
public static String getPassword() {
return password;
}
public static void setPassword(String password) {
MailSender.password = password;
}
public static int getPort() {
return port;
}
public static void setPort(int port) {
MailSender.port = port;
}
public static String getFrom() {
return from;
}
public static void setFrom(String from) {
MailSender.from = from;
}
public static String getTo() {
return to;
}
public static void setTo(String to) {
MailSender.to = to;
}
public static String getAuth() {
return auth;
}
public static void setAuth(String auth) {
MailSender.auth = auth;
}
public static String getDebug() {
return debug;
}
public static void setDebug(String debug) {
MailSender.debug = debug;
}
public static String getSocket_factory() {
return socket_factory;
}
public static void setSocket_factory(String socketFactory) {
socket_factory = socketFactory;
}
public static String getSubject() {
return subject;
}
public static void setSubject(String subject) {
MailSender.subject = subject;
}
public static String getText() {
return text;
}
public static void setText(String text) {
MailSender.text = text;
}

Categories

Resources