Applescript osacompile fails if user input contains apostrophe / single quote
If I was doing something such as this for myself, I would simply write the contents of &quot;code&quot; to a temporary text file then use osacompile to create the AppleScript application bundle and then delete the temporary text file. Doing it in this manner you should not have do deal with the single-quotes passed in a variable.
The following example AppleScript code is just a proof of concept. In Script Editor, just set an appropriate value for the smsNumber variable, for you, and then run the code.
It will create Foobar.app on your Desktop for you to then double-click and see that it sends you the message with the single-quotes in it.
set appName to &quot;Foobar&quot;
set smsNumber to &quot;&quot;
set smsBody to &quot;Here's my email&quot;

set tempAppleScriptCode to ¬
    &quot;/tmp/&quot; &amp; appName &amp; &quot;.applescript&quot;

set saveToPathFileName to POSIX path of ¬
    (path to desktop as text) &amp; appName &amp; &quot;.app&quot;

set myAppleScriptCode to &quot;tell application \&quot;Messages\&quot; 
    set imessageservice to 1st service whose service type = iMessage 
    set iMessageBuddy to buddy \&quot;&quot; &amp; smsNumber &amp; &quot;\&quot; of imessageservice 
    send \&quot;&quot; &amp; smsBody &amp; &quot;\&quot; to iMessageBuddy
end tell&quot;

set tempFileWasWritten to ¬
    (my writeTextToFile(myAppleScriptCode, tempAppleScriptCode, true))

tell application &quot;System Events&quot; to ¬
    set saveToPathFileNameExists to ¬
        (exists item saveToPathFileName)

set saveToPathFileName to saveToPathFileName's quoted form
set tempAppleScriptCode to tempAppleScriptCode's quoted form

if tempFileWasWritten then
    if not saveToPathFileNameExists then
        do shell script &quot;osacompile -o&quot; &amp; space &amp; saveToPathFileName &amp; ¬
            space &amp; tempAppleScriptCode &amp; &quot;;rm&quot; &amp; space &amp; tempAppleScriptCode
    else
        display dialog &quot;The file '&quot; &amp; saveToPathFileName &amp; ¬
            &quot;' already exists!&quot; buttons {&quot;OK&quot;} default button 1 ¬
            with title &quot;The target file already exists!&quot;
    end if
else
    display dialog &quot;An error occured writing to: '&quot; &amp; tempAppleScriptCode &amp; ¬
        &quot;'&quot; buttons {&quot;OK&quot;} default button 1 with title &quot;Error writing to file!&quot;
end if


on writeTextToFile(theText, theFile, overwriteExistingContent)
    try
        set theOpenedFile to open for access POSIX file theFile with write permission
        if overwriteExistingContent is true then set eof of theOpenedFile to 0
        write theText to theOpenedFile starting at eof
        close access theOpenedFile
        return true
    on error
        try
            close access file theFile
        end try
        return false
    end try
end writeTextToFile