I am trying to send mail with attachment with dynamic recepients but getting the following error :
I am able to ping the host though.
Following is the stack trace
javax.mail.MessagingException: Exception reading response;
nested exception is:
java.net.SocketException: Connection reset
at com.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java:2460)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2187)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:740)
at javax.mail.Service.connect(Service.java:366)
at javax.mail.Service.connect(Service.java:246)
at javax.mail.Service.connect(Service.java:195)
at javax.mail.Transport.send0(Transport.java:254)
at javax.mail.Transport.send(Transport.java:124)
Below is the code snippet :
protected void Sendmail(String opt,String val)
{
String LogFile = "QAS.log";
String sender = "xyz.com";
String host = "smtp.xyz.com";
Properties prop = System.getProperties();
prop.put("mail.smtp.host", host);
Session session = Session.getDefaultInstance(prop);
try
{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(sender));
Multipart multipart = new MimeMultipart();
BodyPart messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(LogFile);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName("Process_Log");
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(Mail_Notify.substring(0,Mail_Notify.length()-1)));
Transport.send(message);
System.out.println("Mail successfully sent");
}
catch (MessagingException mex)
{
mex.printStackTrace();
}
}
Related
I'm trying to send emails to project managers whenever there is a change in their project staffing. For this i want to send an email from no-reply#example.com, how can i achieve this using spring boot?
Thanks in advance for the suggestions and answers.
Tried something like this:
#RequestMapping(value = "/sendEmail", method = { RequestMethod.GET }, produces = { "application/json" })
public ResponseEntity<CustomResponse> sendEmail() {
LOG.debug("Start sendEmail with data, toAddress");
HttpHeaders httpHeaders = commonUtil.setHeaders();
HttpStatus httpStatus = HttpStatus.OK;
CustomResponse customResp = new CustomResponse();
String description;
try {
String to = "bmanikanta415#gmail.com";
String from = "no-reply#example.com";
Properties props = System.getProperties();
Session session = Session.getDefaultInstance(props, null);
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
msg.setSubject("Your Example.com account has been activated");
msg.setText("This is a test");
Transport.send(msg);
description = Constants.SUCCESS;
customResp = commonUtil.getCustomResponse(httpStatus, description, description);
} catch (
Exception e) {
LOG.error("Exception in sendEmail: {}", e);
description = Constants.FAILED;
customResp = commonUtil.getCustomResponse(httpStatus, description, description);
}
ResponseEntity<CustomResponse> responseEntity = new ResponseEntity<CustomResponse>(customResp, httpHeaders,
httpStatus);
LOG.debug("End sendEmail with return data: {}", responseEntity);
return responseEntity;
}
When I run the following code it seems that the message was sent to the queue but I can not see anythyng on the queue. There is no error, exception durig executing my code.
I use Weblogic server.
This is my code:
private InitialContext getInitialContext() throws NamingException {
Hashtable env = new Hashtable();
env.put(InitialContext.INITIAL_CONTEXT_FACTORY, contextFactory);
env.put(InitialContext.PROVIDER_URL, providerUrl);
env.put(Context.SECURITY_PRINCIPAL, username);
env.put(Context.SECURITY_CREDENTIALS, password);
return new InitialContext(env);
}
public ConnectionFactory getConnectionFactory(InitialContext context) throws NamingException {
return (ConnectionFactory) context.lookup(ConnectionParameter.JMS_CONNECTION_FACTORY_JNDI);
}
public void send() throws NamingException, JMSException {
InitialContext context = getInitialContext();
Destination destination = (Destination) context.lookup("jms/dpdr/mhcinterface/arnoldQueue");
try (Connection connection = getConnectionFactory(context).createConnection();){
Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
MessageProducer sender = session.createProducer(destination);
Message message = session.createTextMessage("work order complete!");
sender.send(message);
session.commit();
session.close();
}
context.close();
System.out.println("-- end --");
}
Any idea what is wrong here please?
It looks like you forgot to call connection.start() before sending your message. You can do it like below:
MessageProducer sender = session.createProducer(destination);
connection.start();
Message message = session.createTextMessage("work order complete!");
I have the below code in a groovy class, I want to call this method asynchronously from various other groovy classes.
public void sendNotification(){
//async true
String from = ApplicationConfig.email_From;
String sendTo = ApplicationConfig.email_To;
String host = ApplicationConfig.email_Host;
String subject = ApplicationConfig.email_Subject;
String textToSend = ApplicationConfig.email_Text;
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
Session session = Session.getDefaultInstance(properties);
try{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(sendTo));
message.setSubject(subject);
message.setText(textToSend);
Transport.send(message);
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
So far I couldn't find anything that fits my requirement, there are some plugins in grails, but I'm not using grails.
Just use an ExecutorService
ExecutorService pool = Executors.newFixedThreadPool(2)
def sender = { ->
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", ApplicationConfig.email_Host);
Session session = Session.getDefaultInstance(properties);
try{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(ApplicationConfig.email_From));
message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(ApplicationConfig.email_To));
message.setSubject(ApplicationConfig.email_Subject);
message.setText(ApplicationConfig.email_Text);
Transport.send(message);
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
public void sendNotification() {
pool.submit(sender)
}
The following code is supposed to send and save messages sent via yahoomail. The sending part works OK but id does not save the sent message. I've been researching and found the following code:
/**
* Read the body of the message until EOF.
*/
public static String collect(BufferedReader in) throws IOException {
String line;
StringBuffer sb = new StringBuffer();
while ((line = in.readLine()) != null) {
sb.append(line);
sb.append("\n");
}
return sb.toString();
}
How do I incorporate it in the following code?
public void doSendYahooMail(){
from = txtFrom.getText();
password= new String(txtPassword.getPassword());
to = txtTo.getText();
cc = txtCC.getText();
bcc = txtBCC.getText();
subject = txtSubject.getText();
message_body = jtaMessage.getText();
//String imapHost = "imap.mail.yahoo.com";
Properties props = new Properties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", "smtp.mail.yahoo.com");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.imap.host", "imap.mail.yahoo.com");
props.put("mail.imap.ssl.enable", "true");
props.put("mail.imap.port", "993");
Session session = Session.getInstance(props,null);
try {
// message definition
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(to));
if(!cc.equals("")){
message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc));
}
if(!bcc.equals("")){
message.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc));
}
message.setSubject(subject);
if(!filename.equals("")){// if a file has been attached...
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(message_body);// actual message
Multipart multipart = new MimeMultipart();// create multipart message
// set the text message part
multipart.addBodyPart(messageBodyPart);//add the text message to the multipart
// attachment part
messageBodyPart = new MimeBodyPart();
String attachment = fileAbsolutePath;
DataSource source = new FileDataSource(attachment);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);//add the attachment to the multipart message
// combine text and attachment
message.setContent(multipart);
// send the complete message
Transport.send(message, from, password);
}
else{// if no file has been attached
message.setText(message_body);
Transport.send(message, from, password);
}
JOptionPane.showMessageDialog(this, "Message Sent!","Sent",JOptionPane.INFORMATION_MESSAGE);
filename = "";//reset filename to null after message is sent
fileAbsolutePath = "";//reset absolute path name to null after message is sent
// save sent message
Store store = session.getStore("imap");
store.connect(from, password);
Folder folder = store.getFolder("Sent");
if(!folder.exists()){
folder.create(Folder.HOLDS_MESSAGES);
Message[] msg = new Message[1];
msg[0] = message;
folder.appendMessages(msg);
}
store.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(this, e.toString());
}
}
I have my socket closed or reset by peer after a while,I think garbage collection problem through its reader or writer.
Asynctask for handling responses:
#Override
protected Void doInBackground(Void... params) {
//Log.e("NEW LISTENER THREAD NAME", name);
//initializations
try{
clientSocket = new Socket();
//clientSocket.setTcpNoDelay(true);
clientSocket.connect(new InetSocketAddress(serverURL, dataServerPort));
requestSender = new PrintWriter(new PrintStream(clientSocket.getOutputStream(), true,"UTF-8"));
Sender.Init();
}catch(Exception e){
e.printStackTrace();
}
gsonObj = new GsonBuilder().create();//This the object that handels every comming response
finish = false;
try{
listener = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
}catch (IOException e) {
Log.e("FROM CREATING LISTENER", "FROM CREATING LISTENER ========> ");
e.printStackTrace();
}
LOGGED_IN = StaticArea.getLoggedIn(cnt);
if(LOGGED_IN){
USER = StaticArea.getUserName(cnt);
Sender.ResumeUser();
/*********DELEGATING CONNECTING TO SERVER TO BE USED IN SERVICE*************/
Message connectionMsg = new Message();
connectionMsg.obj = Boolean.valueOf(true);
serviceHandler.handleMessage(connectionMsg);
/*********END DELEGATING CONNECTING TO SERVER*************/
}else{
/*********DELEGATING CONNECTING TO SERVER TO BE USED IN SERVICE*************/
Message connectionMsg = new Message();
connectionMsg.obj = Boolean.valueOf(false);
serviceHandler.handleMessage(connectionMsg);
/*********END DELEGATING CONNECTING TO SERVER*************/
}
GoOnline();
while(!finish){
try{
answerS = listener.readLine();
if(answerS != null )//to avoid any null response
if(answerS.contains(Response.MYRESPONSE){
if(MyService.theHandler != null){
Message msg = new Message();
msg.obj = answerS;
MyService.theHandler.sendMessage(msg);
The Sender class is class that has a static methods and uses my sockets output:
public class Sender {
private static Gson gsonObj;
public static void Init() {
gsonObj = new GsonBuilder().create();
}
public static void SendTestRequest(){
try{
Request req = new Request();
req.setR_TYPE(Request.TEST);
String reqString = gsonObj.toJson(req);
requestSender.println(reqString);
requestSender.flush();
}catch(Exception e){
}
}//end method