Du er her: Hjem > Sharepoint > Javascript til Content Editor Webparts > E-mail fra et listeelement

E-mail fra et listeelement

Kode til at oprette og sende en email, med indhold fra et valgt listelement. Koden skal sættes ind på en side i en Content Editor Webpart.
Selve siden skal have et URL-parameter Id, der indeholder item id for det listeelement der skal vises, f.eks.:

https://mysite.sharepoint.com/SitePages/EmailListItem.aspx?Id=2

Koden skal konfigureres med følgende parametre:

Variabel Linjenjummer Bemærkning
VJBSCode.SpEmailListItem.MailHeader 97 Mailens heeader tekst
VJBSCode.SpEmailListItem.MailFooter 100 Mailens footer tekst
VJBSCode.SpEmailListItem.TargetListName 103 Navn til den liste der skal genereres emails fra
VJBSCode.SpEmailListItem.TargetListColumns 106 Statiske navne til alle kolonner der skal medtages i mailen
VJBSCode.SpEmailListItem.TargetListReceiverColumn 109 Den kolonne, hvor modtager findes. Dette skal være en Person kolonne, med kun én værdi

Webdelen vises som en forhåndsudfyldt formular, hvor kolonnenavne og kolonnedata vises i teksten, samt den header og footer der er defineret i de variabler som er nævnt i tabellen overfor.

Kodelinjer med konfigurable variabler:

EmailListItem variables

EmailListItem formula

Man vil kunne finde værdier fra liste, inde i mailteksten:

EmailListItem list item and formula

 Selve koden kan hentes her.

<!--
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Vidar Jon Bauge <vidarjb@gresshoppen.dk>
-->
<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
 
<div id="mailformula" class="mailformula">
<div class="mailformula">
 Receivers
<br/>
 Separate every recipient with a comma.
</div>
<div class="mailformula">
<input id="inputReceivers" class="mailInputFormula" required="required"/>
</div>
<div class="mailformula">
 Subject
</div>
<div class="mailformula">
<input id="inputSubject" class="mailInputFormula" required="required"/>
</div>
<div class="mailformula">
 Body
</div>
<div class="mailformula">
<textarea id="inputBody" rows="20" class="mailInputFormula"></textarea>
</div>
<div class="buttonSection">
<div style="float:left;">
<a class="sendMailButton" href="javascript:VJBSCode.SpEmailListItem.SendButtonClicked();">Send</a>
</div>
<div style="float:right;">
<a class="sendMailButton" href="javascript:VJBSCode.SpEmailListItem.MailClientButtonClicked();">Open in mail program</a>
</div>
</div>
</div>
 
<style type="text/css">
.mailformula{
width:98%;
}
.mailInputFormula{
width:98%;
}
.buttonSection{
width:98%;
margin-top:20px;
}
.sendMailButton{
padding:4px6px4px2px;
border:solid1px#000000;
color:#000000;
background-color:#ffffff;
text-decoration:none;
}
.sendMailButton:hover {
padding:4px6px4px2px;
border:solid1px#000000;
color:#0072C6;
background-color:#ffffff;
text-decoration:none;
}
</style>
 
<script
type = "text/javascript" >Type.registerNamespace('VJBSCode');
VJBSCode.SpEmailListItem = VJBSCode.SpEmailListItem || {};
 
// Header text
VJBSCode.SpEmailListItem.MailHeader = "Mail regarding list item";
 
// Footer text
VJBSCode.SpEmailListItem.MailFooter = "Regards from the Sharepoint Team";
 
// Name of the target list
VJBSCode.SpEmailListItem.TargetListName = "TestList";
 
// All columns to be included in the mail body. Always use the static name of the columns!!
VJBSCode.SpEmailListItem.TargetListColumns = ["Title", "Description", "Start_x0020_Date", "End_x0020_Date", "Manager", "Modified", "Created", "Author", "Editor"];
 
// The column containing the receiver
VJBSCode.SpEmailListItem.TargetListReceiverColumn = "Manager";
 
VJBSCode.SpEmailListItem.ItemId = "";
VJBSCode.SpEmailListItem.TargetListItem = "";
VJBSCode.SpEmailListItem.TargetListItemAsText = "";
VJBSCode.SpEmailListItem.TargetList = "";
VJBSCode.SpEmailListItem.TargetListFields = "";
 
VJBSCode.SpEmailListItem.GetListItem = function() {
 VJBSCode.SpEmailListItem.ItemId = VJBSCode.SpEmailListItem.GetUrlParameter("Id");
 
if (VJBSCode.SpEmailListItem.ItemId === ""|| VJBSCode.SpEmailListItem.ItemId == null) {
 alert("No item sent to this page!");
return;
}
 
 console.log("Requesting list item "+ VJBSCode.SpEmailListItem.ItemId);
var clientContext = new SP.ClientContext.get_current();
var web = clientContext.get_web();
 
VJBSCode.SpEmailListItem.TargetList = web.get_lists().getByTitle(VJBSCode.SpEmailListItem.TargetListName);
VJBSCode.SpEmailListItem.TargetListFields = VJBSCode.SpEmailListItem.TargetList.get_fields();
VJBSCode.SpEmailListItem.TargetListItem = VJBSCode.SpEmailListItem.TargetList.getItemById(VJBSCode.SpEmailListItem.ItemId);
VJBSCode.SpEmailListItem.TargetListItemAsText = VJBSCode.SpEmailListItem.TargetListItem.get_fieldValuesAsText();
 
clientContext.load(VJBSCode.SpEmailListItem.TargetListItemAsText);
clientContext.load(VJBSCode.SpEmailListItem.TargetListFields);
clientContext.load(VJBSCode.SpEmailListItem.TargetListItem);
clientContext.executeQueryAsync(Function.createDelegate(this, this.VJBSCode.SpEmailListItem.OnQuerySucceeded), Function.createDelegate(this, this.VJBSCode.SpEmailListItem.OnQueryFailed));
};
 
VJBSCode.SpEmailListItem.OnQuerySucceeded = function() {
 console.log("Request for list item succeeded.");
 
var itemReceiver = VJBSCode.SpEmailListItem.TargetListItem.get_item(VJBSCode.SpEmailListItem.TargetListReceiverColumn).get_email();
var mailSubject = "Mail regarding "+ VJBSCode.SpEmailListItem.TargetListItem.get_item("Title") + " with id "+ VJBSCode.SpEmailListItem.TargetListItem.get_id();
 
var mbody = "";
 
var fieldEnumerator = VJBSCode.SpEmailListItem.TargetListFields.getEnumerator();
 
while (fieldEnumerator.moveNext()) {
var itemColumn = fieldEnumerator.get_current();
 
if (!itemColumn.get_hidden()) {
var internalName = itemColumn.get_internalName();
if (jQuery.inArray(internalName, VJBSCode.SpEmailListItem.TargetListColumns) !== -1) {
var displayName = itemColumn.get_title();
var content = VJBSCode.SpEmailListItem.TargetListItemAsText.get_item(internalName);
mbody = mbody + displayName + ": "+ content + "\n";
}
 }
 }
 
var mailBody = VJBSCode.SpEmailListItem.MailHeader + "\n\n";
mailBody = mailBody + mbody + "\n"+ VJBSCode.SpEmailListItem.MailFooter + "\n";
 
$("#inputReceivers").val(itemReceiver);
$("#inputSubject").val(mailSubject);
$("#inputBody").text(mailBody);
};
 
VJBSCode.SpEmailListItem.OnQueryFailed = function(sender, args) {
 console.log('Request failed.'+ args.get_message());
};
 
VJBSCode.SpEmailListItem.GetUrlParameter = function(parameterName) {
var url = location.href;
parameterName = parameterName.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var expression = "[\\?&]"+ parameterName + "=([^&#]*)";
var regex = new RegExp(expression);
var results = regex.exec(url);
return results === null ? null : results[1];
};
 
VJBSCode.SpEmailListItem.SendButtonClicked = function() {
 console.log("Send button clicked");
var receivers = $("#inputReceivers").val();
var subject = $("#inputSubject").val();
var body = $("#inputBody").val();
var body = body.replace(/\r\n|\r|\n/g, "<br/>");
 
console.log("Trying to send mail");
VJBSCode.SpEmailListItem.SendEmail(receivers.split(","), body, subject);
};
 
VJBSCode.SpEmailListItem.MailClientButtonClicked = function() {
var receivers = $("#inputReceivers").val();
var subject = $("#inputSubject").val();
var body = $("#inputBody").val();
 
body = body.replace(/<br\s*[\/]?>/gi, "\r\n");
body = encodeURIComponent(body);
 
var mailLink = "mailto:"+ receivers + "?subject="+ subject + "&body="+ body;
window.location.href = mailLink;
};
 
VJBSCode.SpEmailListItem.SendEmail = function(receiver, body, subject) {
 siteUrl = window.location.protocol + "//"+ window.location.host + _spPageContextInfo.siteServerRelativeUrl;
var urlTemplate = siteUrl + "/_api/SP.Utilities.Utility.SendEmail";
$.ajax({
 contentType : 'application/json',
 url : urlTemplate,
 type : "POST",
 data : JSON.stringify({
'properties' :{
'__metadata' :{
'type' :'SP.Utilities.EmailProperties'
},
'To' :{
'results' :receiver
 },
'Body' :body,
'Subject' :subject
 }
 }),
 headers : {
"Accept" :"application/json;odata=verbose",
"content-type" :"application/json;odata=verbose",
"X-RequestDigest" :$("#__REQUESTDIGEST").val()
 },
 success : function(data) {
 alert("The mail was sent");
console.log('success');
},
 error : function(err) {
 alert("An error occurred. The mail could not be sent\nOpening mail program.");
VJBSCode.SpEmailListItem.MailClientButtonClicked();
}
 });
};
 
SP.SOD.executeOrDelayUntilScriptLoaded(VJBSCode.SpEmailListItem.GetListItem, "sp.js");
</script>