Ana içeriğe geç

Sending Email with JSON Format Message

Groovy Script

import javax.mail.*
import javax.mail.internet.*
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

/*
Request:
{
"gonderen":"bilgi.apinizer",
"alicilar":"info@apinizer.com",
"bilgiAlicilar":null,
"gizliAlicilar":null,
"konu":"test",
"icerik":"test",
"icerikTuru":"text/html;charset=utf-8"
}

Response:
{
"islemBasariliMi":true,
"hataMesaji":"",
"hataKodu":""
}
*/

try {
requestHeaderMapFromClient.put('statusCode',0)
def jsonSlurper = new JsonSlurper()
def jsonMessage = jsonSlurper.parseText(requestBodyTextFromClient)

String from=jsonMessage.gonderen
if(from.equals("bilgi.apinizer")){
from="info@apinizer.com"
}else if(from.equals("apinizer.hata")){
from="warning@apinizer.com"
} else{
statusCode=400
requestErrorMessageFromClient = JsonOutput.toJson([islemBasariliMi: false, hataMesaji: 'Hatalı gönderen bilgisi', hataKodu:'01-ERR-02'])
return
}

String to=jsonMessage.alicilar
String cc=jsonMessage.bilgiAlicilar
String bcc=jsonMessage.bilgiAlicilar

if(!to?.trim()&& !cc?.trim()&& !bcc?.trim()){
requestErrorMessageFromClient = JsonOutput.toJson([islemBasariliMi: false, hataMesaji: 'En az bir alıcı eklenmeli', hataKodu:'01-ERR-03'])
statusCode=400
return
}

String subject=jsonMessage.konu
if(subject?.trim()){
subject=""
}

String content=jsonMessage.icerik
if(content?.trim()){
content=""
}

String mimeType=jsonMessage.icerikTuru
if(mimeType?.trim()){
mimeType="text/html;charset=utf-8"
}

// Init constants of sender email account.
String email = "apinizer.hata"
String password = ""
String host = "mail.apinizer.com"
String port = "25" // "465" "587"

// Set up properties.
Properties props = System.getProperties()
props.put("mail.smtp.user", email)
props.put("mail.smtp.host", host)
props.put("mail.smtp.port", port)
props.put("mail.smtp.auth", "false")
props.put("mail.smtp.starttls.enable", "false")
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory")
props.put("mail.smtp.ssl.trust", host)
// Change host to "*" if you want to trust all host.

Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(email, password)
}
})

// Set up message.
MimeMessage message = new MimeMessage(session)
message.setFrom(new InternetAddress(from))
if(to?.trim()){
message.addRecipients(Message.RecipientType.TO, new InternetAddress(to))
}
if(cc?.trim()){
message.addRecipients(Message.RecipientType.CC, new InternetAddress(cc))
}
if(bcc?.trim()){
message.addRecipients(Message.RecipientType.BCC, new InternetAddress(bcc))
}
message.setSubject(subject)
message.setContent(content, mimeType)

try {
// Send mail.
Transport.send(message )
} catch (MessagingException e) {
e.printStackTrace()
statusCode=500
requestErrorMessageFromClient = JsonOutput.toJson([islemBasariliMi: false, hataMesaji: 'Mail gönderirken hata oluştu:' + e.getMessage(), hataKodu:'01-ERR-04'])
return
}

statusCode=200
requestErrorMessageFromClient = JsonOutput.toJson([islemBasariliMi: true, hataMesaji: '', hataKodu:''])
} catch (MessagingException e) {
e.printStackTrace()
statusCode=500
requestErrorMessageFromClient = JsonOutput.toJson([islemBasariliMi: false, hataMesaji: 'Mail gönderirken hata oluştu:' + e.getMessage(), hataKodu:'01-ERR-05'])
return
}

Explanation

This script performs the following operations:

  1. JSON Parse: JSON message coming from request body is parsed
  2. Sender Validation: Sender information is checked and converted to email address
  3. Recipient Check: At least one recipient (TO, CC or BCC) must exist
  4. Email Sending: Email is sent via SMTP
  5. Response Creation: Operation result is returned as response in JSON format

Sample Request

{
"gonderen": "bilgi.apinizer",
"alicilar": "info@apinizer.com",
"bilgiAlicilar": null,
"gizliAlicilar": null,
"konu": "test",
"icerik": "test",
"icerikTuru": "text/html;charset=utf-8"
}

Sample Response

{
"islemBasariliMi": true,
"hataMesaji": "",
"hataKodu": ""
}
not

This script should be run on the request line (Request Policy) because it uses the requestBodyTextFromClient and requestErrorMessageFromClient variables.