email from SQL ASP - sql

I have a web portal based upon a SQL database, that we use to update progress. When a record has been updated in the queue the web form is supposed to send an email message.
Currently the web portal is not sending the message, and I am not sure of the point of failure. The portal itself is being updated as I can see the updated record in the SQL table. Just not receiving the email.
Update 04/27/18
So I am trying to attack this from a new avenue, and it is working kind of....
What I have done, is sent the form off to an external website using php, and it will send an email.
What I am wondering is how can I pass variables? I have been reading instructions for an hour, and it just doesn't make sense to me.
Essentially I want to pass one variable from the following query
thequery = "SELECT loginemail FROM users WHERE referrerId = " & request.Form("referrerID") & ""
objRS.open thequery, objConn, adOpenStatic, adLockReadOnly
and then pass it with something like this
<form action="https://xxxxxx.com/hello.php?loginemail" method="post" name="updateclientform" id="updateclientform">
On the php form side send the email based upon the variable "loginemail"
$to = trim(objRS("loginemail"));
Anyone help? PLEASE

CDO may not be supported by MS anymore - like Classic ASP itself, but it still works. I would look into a setting up a script in your ASP application to send the mail using CDO. That way you can better control any SQL injection threats and manage the whole process in one place.
Here is an example CDO mail script.
<%
'* Declare mailobject variables.
Dim validEmail, email_to, objCDOMail, objConf
Sub SetMailObject()
'* set up CDO config
Set objConf=Server.CreateObject("CDO.Configuration")
objConf.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
objConf.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "mysmtp.server.com"
objConf.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1
objConf.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "myusername"
objConf.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "mypassword"
objConf.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
objConf.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = False
objConf.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = 60
objConf.Fields.Update
' Create an instance of the NewMail object.
Set objCDOMail = Server.CreateObject("CDO.Message")
Set objCDOMail.Configuration=objConf
End Sub
Sub sendLoginEmail(email_to)
'* Call Sub to set mail object settings
SetMailObject()
'* Set the mail objects
objCDOMail.From = "myadmin#mydomain.com"
objCDOMail.To = email_to
objCDOMail.Bcc = ""
objCDOMail.Subject = "My mail subject"
objCDOMail.TextBody = "My email body"
'* Send the message
objCDOMail.Send
'* Set the object to nothing
Set objCDOMail = Nothing
End Sub
If Request("loginemail") <> "" Then
validEmail = Request("loginemail")
'* strongly suggest to perform some cleansing and validation of the email here
Call sendLoginEmail(validEmail)
End If
%>

Related

How will affect Lotus Notes GetDatabase parameters my notes account?

I would like to send e-mail with excel macro. I have read on some websites the same simple VBA code which can send the e-mail with attachment.
Sub Send_Email_via_Lotus_Notes()
Dim Maildb As Object
Dim MailDoc As Object
Dim Body As Object
Dim Session As Object
'Start a session of Lotus Notes
Set Session = CreateObject("Lotus.NotesSession")
'This line prompts for password of current ID noted in Notes.INI
Call Session.Initialize
'or use below to provide password of the current ID (to avoid Password prompt)
'Call Session.Initialize("<password>")
'Open the Mail Database of your Lotus Notes
Set Maildb = Session.GETDATABASE("", "D:\Notes\data\Mail\eXceLiTems.nsf")
If Not Maildb.IsOpen = True Then Call Maildb.Open
'Create the Mail Document
Set MailDoc = Maildb.CREATEDOCUMENT
Call MailDoc.REPLACEITEMVALUE("Form", "Memo")
'Set the Recipient of the mail
Call MailDoc.REPLACEITEMVALUE("SendTo", "Ashish Jain")
'Set subject of the mail
Call MailDoc.REPLACEITEMVALUE("Subject", "Subject Text")
'Create and set the Body content of the mail
Set Body = MailDoc.CREATERICHTEXTITEM("Body")
Call Body.APPENDTEXT("Body text here")
'Example to create an attachment (optional)
Call Body.ADDNEWLINE(2)
Call Body.EMBEDOBJECT(1454, "", "C:\dummy.txt", "Attachment")
'Example to save the message (optional) in Sent items
MailDoc.SAVEMESSAGEONSEND = True
'Send the document
'Gets the mail to appear in the Sent items folder
Call MailDoc.REPLACEITEMVALUE("PostedDate", Now())
Call MailDoc.SEND(False)
'Clean Up the Object variables - Recover memory
Set Maildb = Nothing
Set MailDoc = Nothing
Set Body = Nothing
Set Session = Nothing
End Sub
Set Maildb = Session.GETDATABASE("", "D:\Notes\data\Mail\eXceLiTems.nsf")
On my working laptop there are 10 nsf file. I dont know which should I put in the second parameter.
I have read the syntax here: https://help.hcltechsw.com/dom_designer/9.0.1/appdev/H_GETDATABASE_METHOD.html
Both can be empty string. If i would use empty string it creates a new database if I am correct. Because I would like to send each day 5 emails, I would like to send e-mails in for loop. If I use empty string, the code will create each day 5 database? I think yes, so I think I need one of the 10 nsf file use in as second parameter, so it will not create, but I dont want to crash my notes account with this.
I am quite new to notes. I used vba for outlook to send emails, and there was no database parameters.
First of all: GetDatabase will NEVER create a new database. If the database you enter exists, then your OBJECT (not the real thing, just a variable) will be created and the isOpen- Property will be true, otherwise it will be false.
You need to decide, where you want to (at least temporarily) STORE the mails you are sending.
If you set SaveMessageOnSend = True then it will be saved in that database, if you set it to False, then it will only be created in memory and NOT saved, but still you need a container for that "in Memory"- document.
Usually Mails that are created programmatically will be saved in the users' mailfile (in that case: in YOUR mailfile.
The right code for this would be:
'Initialize object without really opening a database
Set Maildb = Session.GETDATABASE("", "")
'Now open the users' mailfile
Call Maildb.OpenMail
If you have some "dummy" database to create your mails in, then you need to CREATE that database before running your script (within Notes\Data - Directory) using your Notes Client and open that one:
If you e.g. create it in mail- subdirectory of Notes\Data then it might have the absolute Path like:
C:\Program Files (x86)\HCL\Notes\Data\mail\dummy.nsf
In your script you can address it using a relative path (starting from data):
Set Maildb = Session.GETDATABASE("", "mail\dummy.nsf")
or an absolute path (doesn't really matter) like:
Set Maildb = Session.GETDATABASE("", "C:\Program Files (x86)\HCL\Notes\Data\mail\dummy.nsf")
no need of "OpenMail"- command in that case as you do not want to use the users' mailfile but the explicitely given one...
One more thing: Call MailDoc.SEND(False) already creates a PostedDate- item on your mail. No need to use the line Call MailDoc.REPLACEITEMVALUE("PostedDate", Now()).

How to automatically classify the Outlook email sensitivity for Azure Information Protection in VB.Net?

I'm developing a windows from using vb.net, trying to send an email through outlook. My code is running fine, but once it reaches the send() line, a pop-up of Azure Information Protection to select the email sensitivity (Public, Confidential, ...etc), so the email will not be sent until a user select.
I tried ( OutlookMessage.Sensitivity = outlook.OlSensitivity.olNormal )
but still, need some one to select the classification from the Azure pop-up, full code shown below...
Dim OutlookMessage As outlook.MailItem
Dim AppOutlook As New outlook.Application
Try
OutlookMessage = AppOutlook.CreateItem(outlook.OlItemType.olMailItem)
Dim Recipents As outlook.Recipients = OutlookMessage.Recipients Recipents.Add("myemail#hotmail.com")
OutlookMessage.Subject = "Sending through Outlook"
OutlookMessage.Body = "Testing outlook Mail"
OutlookMessage.BodyFormat = outlook.OlBodyFormat.olFormatHTML
OutlookMessage.Sensitivity = outlook.OlSensitivity.olNormal
OutlookMessage.Send()
Catch ex As Exception
MessageBox.Show("Mail could not be sent") 'if you dont want this message, simply delete this line
Finally
OutlookMessage = Nothing
AppOutlook = Nothing
End Try
Hoping that the code runs using a service account, do the below
Add the above service account inside the scoped AIP policy
Set a default label in the scoped policy
Doing this will not trigger the popup as a default label is already applied (I hope).
Note: You can set different default labels for Outlook and other MS apps using AIp Policy's advanced settings

No RFC authorization for function module RFC PING from VBA?

Good morning, everybody!
I've been looking for the solution in the last days but I really have not managed to succeed: I am trying to make a VBA code to:
log into SAP,
run some transactions,
export to excel.
But even the "log into SAP" part is not OK!
I tried several codes, the one below OPENS the SAP logon screen, but does not fill in any fields.
In the first attempt, I Used CreateObject("Sapgui.ScriptingCtrl.1"):
Sub Entrar_SAP()
If Not IsObject(SAPguiApp) Then
Set SAPguiApp = CreateObject("Sapgui.ScriptingCtrl.1")
End If
If Not IsObject(Connection) Then
Set Connection = SAPguiApp.OpenConnection("xxxxxxx)", True)
End If
If Not IsObject(session) Then
Set session = Connection.Children(0)
End If
session.findById("wnd[0]/usr/txtRSYST-MANDT").Text = "100"
session.findById("wnd[0]/usr/txtRSYST-BNAME").Text = "user"
session.findById("wnd[0]/usr/pwdRSYST-BCODE").Text = "pass"
session.findById("wnd[0]/usr/txtRSYST-LANGU").Text = "PT"
session.findById("wnd[0]/usr/txtRSYST-LANGU").SetFocus
session.findById("wnd[0]/usr/txtRSYST-LANGU").caretPosition = 2
session.findById("wnd[0]").sendVKey 0
In the second attempt, I tried CreateObject("SAP.Functions"), it showed:
"RFC error received. No RFC authorization for function module RFC PING"
The code is:
'Declaration
Dim objBAPIControl As Object 'Function Control (Collective object)
Dim sapConnection As Object 'Connection object
Set objBAPIControl = CreateObject("SAP.Functions")
Set sapConnection = objBAPIControl.Connection
sapConnection.Client = "xxxxx"
sapConnection.User = "xxxxxx"
sapConnection.Language = "PT"
sapConnection.hostname = "xxxxx"
sapConnection.Password = "xxxxxxxx" 'Fake password
sapConnection.SystemNumber = "4"
sapConnection.System = "xxxxxx)"
sapConnection.Logon
If sapConnection.Logon(1, True) <> True Then
MsgBox "No connection to R/3!"
Exit Sub 'End program
End If
Can someone please help me? Thanks!!
First of all, RFC is a perfectly fine method for interacting with SAP. It's not out of support.
Second, you don't have enough authorization so your code will not work even if you get the syntax right. "RFC error received. No RFC authorization for function module RFC PING". Ask your SAP team to give you access to execute RFCs remotely. Ask for SAP_S_RFCACL.
On a side note, your main object of running some transactions and exporting to Excel is quite easy to do in SAP. Maybe you should just ask your SAP team to do it for you instead of developing it in VBA?
I assume your pulling via an RFC read Table. This Connection will work fine for those.
Dim LogonControl As Object
Dim conn As Object
Dim retcd As Boolean
Set LogonControl = CreateObject("SAP.LogonControl.1")
Set conn = LogonControl.NewConnection
conn.System = "strSystemName"
conn.Client = "100"
conn.Language = "EN"
conn.User = "sUserName"
conn.Password = "strPassword"
retcd = conn.Logon(0, True) 'True = No logon GUI 'False = logon GUI
If retcd <> True Then
MsgBox "Login failed for- " & strSystemName & " -UserName or Password are incorrect, check them and run try again ."
Exit Sub
End If
Set funcControl = CreateObject("SAP.Functions")
funcControl.Connection = conn
From this Point on you can make your RFC call without any issues.
But to be truthful though, Above is almost exactly what you have as your second example. your RFC Error your getting seems like you don't have security settings for SAP to make RFC calls to whatever table your pulling from and not a problem with your login code.
Disclaimer: RFC_READ_TABLE is NOT supported by SAP and is more of a backdoor then a day to day method for pulling data.
Edit1: To Cover the Comments and not turn this into a discussion I will try and Summarize them here.
Firstly
the pop-up: If you want the pop-up for the log in then you need to change this line of code
retcd = conn.Logon(0, True)
to
retcd = conn.Logon(0, False) 'This one DISPLAYS the pop-up
Secondly
The Permissions: RFC_Read_Table uses Very Different Security Settings then a SAP t-Code uses, The technical Difference is difficult to explain but for a rule of thumb, If you cant access the SAP Table (t-Code SE16) you most likely not be able to pull it from RFC Read Table
Thirdly
If your company has Multiple SAP boxes (DEV, production, test) the Systemname would be EXACTLY what shows up on the box selection screen of SAP under name. assuming you were getting an RFC error from your second code block then the box name you used in that code would be the correct one.
You can bypass RFC controls and just go for a normal scripting that imitates a human user and manually introduces username and password. Credit to The Script Man from the SAP forums:
Sub SapLogin()
'Logs onto SAP system
Dim SapGuiApp As Object
Dim oConnection As Object
Dim session As Object
Dim SAPCon As Object, SAPSesi As Object
Dim SAPGUIAuto As Object, SAPApp As Object
Dim system As String
system = "XX" 'SAP system you will log on to like "01. ENGINEERING PRODUCTION [EG1]
If SapGuiApp Is Nothing Then
Set SapGuiApp = CreateObject("Sapgui.ScriptingCtrl.1")
End If
If oConnection Is Nothing Then
Set oConnection = SapGuiApp.OpenConnection(system, True)
End If
If SAPSesi Is Nothing Then
Set SAPSesi = oConnection.Children(0)
End If
Application.DisplayAlerts = FALSE
With SAPSesi
.FindById("wnd[0]/usr/txtRSYST-MANDT").Text = "100"
.FindById("wnd[0]/usr/txtRSYST-BNAME").Text = "USERNAME"
.FindById("wnd[0]/usr/pwdRSYST-BCODE").Text = "PASSWORD"
.FindById("wnd[0]/usr/txtRSYST-LANGU").Text = "EN"
.FindById("wnd[0]").SendVKey 0
'start extraction
.FindById("wnd[0]").Maximize
.FindById("wnd[0]/tbar[0]/okcd").Text = "/TCODEYOUWANTTORUN"
.FindById("wnd[0]").SendVKey 0
'...
'etc
'...
End With
Application.DisplayAlerts = True
MsgBox "After clicking OK, this SAP session is terminated."
End Sub

How to get the email address of the current logged-in user?

I'm new to VBA and trying to get an automated word document working. At the moment there is a Button in the document that which upon pressing, will fire off an email with the document attached.
However I need to also get the email address of the current user sending the email, so I can place it inside the document before sending it off. My searches on the internet have not resulted in any usable code that meets my situation. My current code is below.
Set OL = CreateObject("Outlook.Application")
Set EmailItem = OL.CreateItem(olMailItem)
Set Doc = ActiveDocument
Doc.Save
With EmailItem
.Subject = "Requesting Authorization Use Overtime"
.Body = "Please review the following request for overtime" & vbCrLf & _
"" & vbCrLf & _
"Thanks"
.To = "toemail#test.com"
.Importance = olImportanceNormal
.Attachments.Add Doc.FullName
.Send
End With
Not sure if this is relevant, but when the document is being used, the Outlook application will always be open with a user signed in. Im used to having intellisense help in these sorts of situations so I can fool around with methods and properties, but there seems to be very little help from intellisense.
It all depends on the definition of "the current user address".
The address of the primary account in Outlook can be retrieved from Appication.Session.CurrentUser (returns Recipient object). Use Recipient.Address property. Note however that for an Exchange account (Recipient.AddressEntry.Type == "EX") you will receive an EX type address. To retrieve the SMTP address, use Recipient.AddressEntry.GetExchangeUser().PrimarySmtpAddress. Be prepared to handle nulls/exceptions in case of errors. This is what you most likely need in your particular case.
On the Extended MAPI level (C++ or Delphi), use IMAPISession::QueryIdentity (you can test it in OutlookSpy (I am its author) - click IMAPISession button, then QueryIdentity). You can then read the PR_ADDRTYPE property ("EX" vs "SMTP") and PR_EMAIL_ADDRESS (when PR_ADDRTYPE = "SMTP") or (in case of Exchange) PR_SMTP_ADDRESS (not guaranteed to be present) and PR_EMS_AB_PROXY_ADDRESSES (multivalued property will Exchange addresses, including all proxy (alias) addresses).
In case of multiple accounts in the profile, an email can be sent or received through multiple accounts. In that case use MailItem.SendUsingAccount (returns Account object, can be null - in that case use Application.Session.CurentUser). This is valid both for received, sent or emails being composed (Application.ActiveInspector.CurrentItem or Application.ActiveExplorer.ActiveInlineResponse).
All accounts in a given profile can be accessed using the Namespace.Accounts collection (Application.Session.Accounts). Account's address can be accessed using Account.SmtpAddress property.
Note that the Outlook Object Model only exposes mail accounts. Some store accounts (such as PST) are not in the collection since they do not have an intrinsic user identity even if some other accounts (such as POP3/SMTP) can deliver to that store. If you want to access all accounts, you can use Redemption (I am its author) and its RDOSession.Accounts collection (RDOAccounts object).
On the Extended MAPI level, the accounts are exposed through the IOlkAccountManager interface. You can play with it in OutlookSpy if you click the IOlkAccountManager button.
In case of delegate Exchange stores, the store owner is not exposed through the Outlook Object Model. You can either use Extended MAPI (note that the PR_MAILBOX_OWNER_ENTRYID property is only exposed by the online store, it is not available in a cached store). You can parse the Exchange store entry id and extract the EX type address from it. You can then construct the GAL object entry id given the EX address. You can also access the store owner using Redemption and its RDOExchangeMailboxStore object and its Owner property.
Usually, the email address is the name assigned to Outlook Mail Folders.
So try this:
'~~> add these lines to your code
Dim olNS As Outlook.NameSpace
Dim olFol AS Outlook.Folder
Set olNS = OL.GetNamespace("MAPI")
Set olFol = olNS.GetDefaultFolder(olFolderInbox)
MsgBox olFol.Parent.Name '~~> most cases contains the email address
This is assuming your are using Early Bind with the object reference properly set.
Another way to access such info is directly use Namespace properties.
MsgBox olNS.Accounts.Item(1).DisplayName '~~> usually email address
MsgBox olNS.Accounts.Item(1).SmtpAddress '~~> email address
MsgBox olNS.Accounts.Item(1).UserName '~~> displays the user name
I hope any of the above somehow helps.
This answer is for Late Binding so you don't need to have reference libraries. Place the following code in a module:
Dim OL As Object, olAllUsers As Object, oExchUser As Object, oentry As Object, myitem As Object
Dim User As String
Set OL = CreateObject("outlook.application")
Set olAllUsers = OL.Session.AddressLists.Item("All Users").AddressEntries
User = OL.Session.CurrentUser.Name
Set oentry = olAllUsers.Item(User)
Set oExchUser = oentry.GetExchangeUser()
msgbox oExchUser.PrimarySmtpAddress
Functional Approach
To make this a bit more reusable, try any return the email from a function.
Late Binding Example
''
' Creates a new instance of Microsoft Outlook to get the current users
' email address.
' Late Binding Demo.
'
' #exception If any errors it will return an optional parameter for fallback values
''
Public Function GetUsersOutlookEmail(Optional ByVal errorFallback As String = "") As String
On Error GoTo catch
With CreateObject("outlook.application")
GetUsersOutlookEmail = .GetNamespace("MAPI").GetDefaultFolder(olFolderInbox).Parent.Name
End With
Exit Function
catch:
GetUsersOutlookEmail = errorFallback
End Function
Early Binding Example
''
' Creates a new instance of Microsoft Outlook to get the current users
' email address.
' Late Binding Demo.
'
' #reference Microsoft Outlook 16.0 Object Reference
' #exception If any errors it will return an optional parameter for fallback values
''
Public Function GetUsersOutlookEmail(Optional ByVal errorFallback As String = "") As String
On Error GoTo catch
With New Outlook.Application
GetUsersOutlookEmail = .GetNamespace("MAPI").GetDefaultFolder(olFolderInbox).Parent.Name
End With
Exit Function
catch:
GetUsersOutlookEmail = errorFallback
End Function
Error Handling
Anytime you are making an API call like this, there is always a potential for errors to occur. The method I choose for these demos is to provided an optional parameter for a fallback email. This make is dynamic as you can check to see if it is null, or you could provide something such as username Environ("Username") & "#outlook.com"

lotus notes start session

I'm looking for a way to start Lotus Notes and control its utilisation from a vb.net project.
By controlling I mean litle things like getting the window position, closing active document and other stuff.
But the main objective is to start a session.
I'm confused because I tried to use the Lotus Notes Automation Classes dll and nothing worked well...
If anyone had some tips for me, I would apreciate a lot!
Thanks! (by the way, sorry english is not my main language)
In Notes speak, a session is a backend object, not a UI object. What you describe (changing window position, closing active window, etc) is UI functionality.
Notes supports COM, and you have full access to all backend classes. But you don't have access to the UI classes.
Why would you want to automate the actual Notes client? If you describe what you are ultimately wanting to do, perhaps we can help. I am sure that the correct way to solve what you are trying to do is to use the backend classes...
I found a way to start Notes, I needed to use process:
Private Sub StartNotes()
Dim p As Process = New Process()
p.StartInfo.FileName = "C:\Program Files\Notes\notes.exe"
p.StartInfo.Arguments = ""
p.Start()
End Sub
I automate it after using backend classes from lotus and domino dll
Sub Send_Email_via_Lotus_Notes()
Dim Maildb As Object
Dim MailDoc As Object
Dim Body As Object
Dim Session As Object
'Start a session of Lotus Notes
Set Session = CreateObject("Lotus.NotesSession")
'This line prompts for password of current ID noted in Notes.INI
Call Session.Initialize
'or use below to provide password of the current ID (to avoid Password prompt)
'Call Session.Initialize("<password>")
'Open the Mail Database of your Lotus Notes
Set Maildb = Session.GETDATABASE("", "D:\Notes\data\Mail\eXceLiTems.nsf")
If Not Maildb.IsOpen = True Then Call Maildb.Open
'Create the Mail Document
Set MailDoc = Maildb.CREATEDOCUMENT
Call MailDoc.REPLACEITEMVALUE("Form", "Memo")
'Set the Recipient of the mail
Call MailDoc.REPLACEITEMVALUE("SendTo", "Ashish Jain")
'Set subject of the mail
Call MailDoc.REPLACEITEMVALUE("Subject", "Subject Text")
'Create and set the Body content of the mail
Set Body = MailDoc.CREATERICHTEXTITEM("Body")
Call Body.APPENDTEXT("Body text here")
'Example to create an attachment (optional)
Call Body.ADDNEWLINE(2)
Call Body.EMBEDOBJECT(1454, "", "C:\dummy.txt", "Attachment")
'Example to save the message (optional) in Sent items
MailDoc.SAVEMESSAGEONSEND = True
'Send the document
'Gets the mail to appear in the Sent items folder
Call MailDoc.REPLACEITEMVALUE("PostedDate", Now())
Call MailDoc.SEND(False)
'Clean Up the Object variables - Recover memory
Set Maildb = Nothing
Set MailDoc = Nothing
Set Body = Nothing
Set Session = Nothing
End Sub