cancel
Showing results for 
Search instead for 
Did you mean: 

Sending Mails on click of a button

Former Member
0 Kudos

Hi Gurus,

I have a scenario where i need to send email on click of a button. i tried various codes available on SCN, but nothing is working out. Can anyone share document on it? help me out.

Accepted Solutions (0)

Answers (5)

Answers (5)

Former Member
0 Kudos

I am getting the below error also while sending mails.

please help

govardan_raj
Contributor
0 Kudos

hi ,

can  u check the logs or print stack trace so that we can know in which line u r getting the null pointer exceptoion ?

use the below code to print stack trace.

try

{

}

catch(Exception exception)

{

StackTracElement element[] = exception.getStackTrace();

StringBuffer buffer = new StringBuffer();

for(int count = 0 ; count < element.length ; count++)

{

buffer.append(element[i]);

}

wdcomponentAPI.getMessageManager().reportException(buffer.toString(),true);
}

Regards

Govardan

Former Member
0 Kudos

Hi Gurus,

Below is my my code and it is showing This compilation unit indirectly references the missing type javax.activation.Datasource(typically some required class file is referencing a type outside the classpath)

syntax error on token "utsx", "interface", " class" expected.

utsx`x`// ---------------------------------------------------------------------------

// This file has been generated partially by the Web Dynpro Code Generator.

// MODIFY CODE ONLY IN SECTIONS ENCLOSED BY @@begin AND @@end.

// ALL OTHER CHANGES WILL BE LOST IF THE FILE IS REGENERATED.

// ---------------------------------------------------------------------------

package com.lanco;

//

// IMPORTANT NOTE:

// _ALL_ IMPORT STATEMENTS MUST BE PLACED IN THE FOLLOWING SECTION ENCLOSED

// BY @@begin imports AND @@end. FURTHERMORE, THIS SECTION MUST ALWAYS CONTAIN

// AT LEAST ONE IMPORT STATEMENT (E.G. THAT FOR IPrivateZhr_formView).

// OTHERWISE, USING THE ECLIPSE FUNCTION "Organize Imports" FOLLOWED BY

// A WEB DYNPRO CODE GENERATION (E.G. PROJECT BUILD) WILL RESULT IN THE LOSS

// OF IMPORT STATEMENTS.

//

//@@begin imports

import java.io.UnsupportedEncodingException;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.Statement;

import java.util.Date;

import java.util.Properties;

import javax.mail.Message;

import javax.mail.MessagingException;

import javax.mail.Session;

import javax.mail.Transport;

import javax.mail.internet.InternetAddress;

import javax.mail.internet.MimeMessage;

import javax.mail.internet.MimeMessage.RecipientType;

import javax.naming.InitialContext;

import javax.naming.NamingException;

import com.lanco.wdp.IPrivateZhr_formView;

import com.sap.tc.webdynpro.services.sal.um.api.IWDClientUser;

import com.sap.tc.webdynpro.services.sal.um.api.WDClientUser;

import com.sap.tc.webdynpro.services.sal.um.api.WDUMException;

//@@end

//@@begin documentation

//@@end

public class Zhr_formView

{

  /**

   * Logging location.

   */

  private static final com.sap.tc.logging.Location logger =

    com.sap.tc.logging.Location.getLocation(Zhr_formView.class);

  static

  {

    //@@begin id

    String id = "$Id$";

    //@@end

    com.sap.tc.logging.Location.getLocation("ID.com.sap.tc.webdynpro").infoT(id);

  }

  /**

   * Private access to the generated Web Dynpro counterpart

   * for this controller class.  </p>

   *

   * Use <code>wdThis</code> to gain typed access to the context,

   * to trigger navigation via outbound plugs, to get and enable/disable

   * actions, fire declared events, and access used controllers and/or

   * component usages.

   *

   * @see com.lanco.wdp.IPrivateZhr_formView for more details

   */

  private final IPrivateZhr_formView wdThis;

  /**

   * Root node of this controller's context. </p>

   *

   * Provides typed access not only to the elements of the root node

   * but also to all nodes in the context (methods node<i>XYZ</i>())

   * and their currently selected element (methods current<i>XYZ</i>Element()).

   * It also facilitates the creation of new elements for all nodes

   * (methods create<i>XYZ</i>Element()). </p>

   *

   * @see com.lanco.wdp.IPrivateZhr_formView.IContextNode for more details.

   */

  private final IPrivateZhr_formView.IContextNode wdContext;

  /**

   * A shortcut for <code>wdThis.wdGetAPI()</code>. </p>

   *

   * Represents the generic API of the generic Web Dynpro counterpart

   * for this controller. </p>

   */

  private final com.sap.tc.webdynpro.progmodel.api.IWDViewController wdControllerAPI;

 

  /**

   * A shortcut for <code>wdThis.wdGetAPI().getComponent()</code>. </p>

   *

   * Represents the generic API of the Web Dynpro component this controller

   * belongs to. Can be used to access the message manager, the window manager,

   * to add/remove event handlers and so on. </p>

   */

  private final com.sap.tc.webdynpro.progmodel.api.IWDComponent wdComponentAPI;

 

  public Zhr_formView(IPrivateZhr_formView wdThis)

  {

    this.wdThis = wdThis;

    this.wdContext = wdThis.wdGetContext();

    this.wdControllerAPI = wdThis.wdGetAPI();

    this.wdComponentAPI = wdThis.wdGetAPI().getComponent();

  }

  //@@begin javadoc:wdDoInit()

  /** Hook method called to initialize controller. */

  //@@end

  public void wdDoInit()

  {

    //@@begin wdDoInit()

try {
IWDClientUser CurrentUser = WDClientUser.getCurrentUser();
euser = WDClientUser.getCurrentUser().getSAPUser().getUniqueName();
fname = WDClientUser.getCurrentUser().getSAPUser().getName();
lname= WDClientUser.getCurrentUser().getSAPUser().getLastName();
}
  catch (WDUMException e)
  {
//TODO Auto-generated catch block
e.printStackTrace();
}

    //@@end

  }

  //@@begin javadoc:wdDoExit()

  /** Hook method called to clean up controller. */

  //@@end

  public void wdDoExit()

  {

    //@@begin wdDoExit()

try{
conn.close();
}catch(Exception eg){
eg.printStackTrace();
}

    //@@end

  }

  //@@begin javadoc:wdDoModifyView

  /**

   * Hook method called to modify a view just before rendering.

   * This method conceptually belongs to the view itself, not to the

   * controller (cf. MVC pattern).

   * It is made static to discourage a way of programming that

   * routinely stores references to UI elements in instance fields

   * for access by the view controller's event handlers, and so on.

   * The Web Dynpro programming model recommends that UI elements can

   * only be accessed by code executed within the call to this hook method.

   *

   * @param wdThis Generated private interface of the view's controller, as

   *        provided by Web Dynpro. Provides access to the view controller's

   *        outgoing controller usages, etc.

   * @param wdContext Generated interface of the view's context, as provided

   *        by Web Dynpro. Provides access to the view's data.

   * @param view The view's generic API, as provided by Web Dynpro.

   *        Provides access to UI elements.

   * @param firstTime Indicates whether the hook is called for the first time

   *        during the lifetime of the view.

   */

  //@@end

  public static void wdDoModifyView(IPrivateZhr_formView wdThis, IPrivateZhr_formView.IContextNode wdContext, com.sap.tc.webdynpro.progmodel.api.IWDView view, boolean firstTime)

  {

    //@@begin wdDoModifyView

    //@@end

  }

  //@@begin javadoc:database()

  /** Declared method. */

  //@@end

  public void database( )

  {

    //@@begin database()

Connection conn=null;
  Statement sqlstat=null;
 
try{
//data base connection statements, organise importa, jar files in navigator
   Class.forName("oracle.jdbc.driver.OracleDriver");
   DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
   conn =DriverManager.getConnection(connectiontext,user,pwd);
   Statement stmt=conn.createStatement();
   sql1= conn.createStatement();
   // getresult();
   }
   catch (Exception e) {
   // TODO: handle exception
   wdComponentAPI.getMessageManager().reportException("Error in database Method",true);
   wdComponentAPI.getMessageManager().reportException(e.toString(),false);
   }

    //@@end

  }

  //@@begin javadoc:sendmail()

  /** Declared method. */

  //@@end

  public void sendmail( )

  {

    //@@begin sendmail()

    //@@end

  }

  //@@begin javadoc:onActionSAVE(ServerEvent)

  /** Declared validating event handler. */

  //@@end

  public void onActionSAVE(com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent )

  {

    //@@begin onActionSAVE(ServerEvent)

   

    IPrivateZhr_formView.IContextElement ele = wdContext.currentContextElement();

    int a = 0;

   

   

    try

    {

Connection conn=null;
  Statement sqlstat=null;

   //data base connection statements, organise importa, jar files in navigator
   Class.forName("oracle.jdbc.driver.OracleDriver");
   DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
   conn =DriverManager.getConnection(connectiontext,user,pwd);
   Statement stmt=conn.createStatement();
   // getresult();
  
  
  
try
{
String queryinsert=null;
String queryselect=null;
queryinsert="insert into ZHR_FORM(EMP_NO,EMP_NAME,DOB)" + "values(?,?,?)";
PreparedStatement pstat=null;
pstat=conn.prepareStatement(queryinsert);
pstat.setInt(1,(ele.getEmp_id()));
pstat.setString(2,(ele.getEmp_name()));
pstat.setDate(3, (ele.getDob()));
a=pstat.executeUpdate();
if(a==1)
{
wdComponentAPI.getMessageManager().reportSuccess("ALL VALUES SAVED SUCCESFULLY");
}
else
{
wdComponentAPI.getMessageManager().reportSuccess("A is not equal to 1");
}
}
catch(Exception ex)
{
wdComponentAPI.getMessageManager().reportException("Saving problem in Form. Contact System administrator ",false);
     wdComponentAPI.getMessageManager().reportException(ex.toString(),false);
    }
   
try {

   InitialContext ctx = new InitialContext();
  
   String sid = System.getProperty("SAPSYSTEMNAME"); // Instance Name

   Properties props = new Properties();
   props.put("mail.smtp.host", "my-mail-server");
   props.put("mail.from", "sender-mail -id");
   Session session = Session.getInstance(props, null);

   try {
  MimeMessage msg = new MimeMessage(session);
  msg.setFrom();
  msg.setRecipients(Message.RecipientType.TO,"receiver-mail-id");
  msg.setSubject("mail-subject");
  msg.setSentDate(new Date());
  msg.setText("SAP Instance name:"+sid);
  Transport.send(msg);
} catch (MessagingException mex)
{
System.out.println("send failed, exception: " + mex);
}

  
  
  
  
  
   //Properties props = System.getProperties();
  
  // props.put("mail.smtp.host", );
   Session _session = Session.getInstance(props,new javax.mail.Authenticator()
   {
//protected PasswordAuthentication.getPasswordAuthentication()
{
//return new   PasswordAuthentication("shilpi.mahajan@lancogroup.com", "XXXXXX");
}
}
);
MimeMessage _message = new MimeMessage(_session);
   _message.setFrom(new InternetAddress("abhishek.mahapatra@tecnics.com"));
   _message.addRecipient(Message.RecipientType.TO, new InternetAddress());
   javax.mail.internet.MimeMultipart content = new  javax.mail.internet.MimeMultipart("alternative");
   _message.setContent(content, "alternative");
   _message.setSubject("BirthDay");
   _message.setDescription("Happy BirthDay");

Transport.send(_message);
System.out.println("Done!!!!!!!!!!!!!!");
// Session session = (Session) javax.rmi.PortableRemoteObject.narrow( ctx.lookup( "java:comp/env/mail/MailSession" ), Session.class );
Session session = Session.getDefaultInstance(props, null);

MimeMessage message = new MimeMessage( session );

   message.setFrom( new InternetAddress("shilpi.mahajan@gmail.com", "Shilpi Mahajan"));

   message.setRecipient(RecipientType.TO, new InternetAddress("shilpi.mahajan@lancogroup.com"));

   message.setSubject("Testmail");

   message.setText("This is a testmail from java.");

   Transport.send(message);

} catch (NamingException e) {
   // TODO Insert some logic
   e.printStackTrace();
  } catch (UnsupportedEncodingException e) {
   // TODO Insert some logic
   e.printStackTrace();
  }
//  catch (MessagingException e) {
//   // TODO Insert some logic
//   e.printStackTrace();
//  }

try
{
conn.close();
}
catch(Exception eg)
{
eg.printStackTrace();
}

    }

catch (Exception ex)
{
// TODO: handle exception
wdComponentAPI.getMessageManager().reportException("Error in database Method",true);
wdComponentAPI.getMessageManager().reportException(ex.toString(),false);
}

    //@@end

  }

  /*

   * The following code section can be used for any Java code that is

   * not to be visible to other controllers/views or that contains constructs

   * currently not supported directly by Web Dynpro (such as inner classes or

   * member variables etc.). </p>

   *

   * Note: The content of this section is in no way managed/controlled

   * by the Web Dynpro Designtime or the Web Dynpro Runtime.

   */

  //@@begin others

//  String connectiontext="jdbc:oracle:thin:@lepdb.lancogroup.net:1527:LEP";

//  String user="epuser";
//  String pwd="userep51";

  String connectiontext="jdbc:oracle:thin:@leapepdv.lancogroup.net:1527:LED";
  String user="epuser";
  String pwd="userep21";
  //String Userid=null;
  Connection conn=null;
Statement sqlstat=null;
Statement sql1=null;
String euser=null;
String fname=null;
String lname=null;

  //@@end

}

Please help me to solve this error. and please tell the steps of the solution.

regards

Shilpi

Former Member
0 Kudos

Hi, Check this code. Properties properties;           

Session session;           

MimeMessage message;  

  // Get system properties

properties = System.getProperties();

// Setup mail server

properties.setProperty("mail.smtp.host", "Smtphostname");

// Get the default Session object.

session = null; session = Session.getDefaultInstance(properties);

// Create a default MimeMessage object.

message = new MimeMessage(session);

message.setFrom("From Email");

// Add the given addresses to the specified recipient type.

message.addRecipient(Message.RecipientType.TO, "ToEmailId");

// Set the "Subject" header field.

message.setSubject("Test Subject");

// Sets the given String as this part's content,

// with a MIME type of "text/plain". 

Multipart multiPart = new MimeMultipart();          

MimeBodyPart messageText = new MimeBodyPart();       

StringBuffer emailBody = new StringBuffer();             

emailBody.append("

");                 emailBody.append("Test body");         emailBody.append("

");         message.setContent(emailBody.toString(), "text/html");                       

multiPart.addBodyPart(messageText);                      

  message.setContent(multiPart);

// Send message

Transport.send(message);

Former Member
0 Kudos

Dear Shilpi,

You can check following document also.

Using JavaMail in Web Dynpro Java Applications for Sending e-mail to Multiple Users -

http://www.sdn.sap.com/irj/scn/go/portal/prtroot/docs/library/uuid/40239f38-a94a-2b10-c583-9b89187c3...

Thanks & Regards,

Patralekha

former_member191044
Active Contributor
0 Kudos

Hi Shilpi,

basically you can play with Java Mail API. Here some code that would send a simple mail:

try {

   InitialContext ctx = new InitialContext();

     Session session = (Session) javax.rmi.PortableRemoteObject.narrow( ctx.lookup( "java:comp/env/mail/MailSession" ), Session.class );

     MimeMessage message = new MimeMessage( session );

   message.setFrom( new InternetAddress("yourMailAddress", "yourName"));

   message.setRecipient(RecipientType.TO, new InternetAddress("receiverMailAddress"));

   message.setSubject("Testmail");

   message.setText("This is a testmail from java.");

   Transport.send(message);

} catch (NamingException e) {

   // TODO Insert some logic

   e.printStackTrace();

  } catch (UnsupportedEncodingException e) {

   // TODO Insert some logic

   e.printStackTrace();

  } catch (MessagingException e) {

   // TODO Insert some logic

   e.printStackTrace();

  }

Hope this helps.

Regards

Tobias

Former Member
0 Kudos

Hi Tobias,

I put ur code in my app, I am facing many errors. Do i need to import some files?

below is the screenshot.

former_member191044
Active Contributor
0 Kudos

Ofcourse you have to import those Classes. As you can see the NWDS provides quick fixes. Just move your cursor on the error and press F1 to see the quickfix.

Maybe you should first do some beginner tutorials to learn some basics.

Regards

Tobias

Former Member
0 Kudos

Dear Shilpi,

Please add the proper jar files to use those JAVA Mail API.

Thanks & Regards,

Patralekha