Jira Script Runner - Mail is not sent by Post Function of Create Transition - email

we have a Project in Jira which we use as an inbox for Email. Not all people sending emails are users in JIRA (and they shall not be). Nevertheless, we would like to inform then on having received the Email. The emailaddress is part of the Issue description.
I am aware of some plugins out there but instead of replacing the Mailhandlers, I am trying to write a groovy script for JIRA adapting this code which I want to post into a Post Function on the CREATE transition of a workflow.
The following code works fine when I grab an existing Test-Issue and run the script in the console:
import com.atlassian.jira.ComponentManager
import com.atlassian.jira.issue.Issue
import com.atlassian.jira.issue.IssueManager
import com.atlassian.mail.Email
import com.atlassian.mail.server.MailServerManager
import com.atlassian.mail.server.SMTPMailServer
ComponentManager componentManager = ComponentManager.getInstance()
MailServerManager mailServerManager = componentManager.getMailServerManager()
SMTPMailServer mailServer = mailServerManager.getDefaultSMTPMailServer()
if (mailServer) {
if (true) {
IssueManager issueManager = componentManager.getIssueManager()
Issue issue = issueManager.getIssueObject("IN-376")
def grabEmail = {
(((it.split( "\\[Created via e-mail received from:")[1]).split("<")[1]).split(">")[0])
}
String senderAddress = grabEmail("${issue.description}")
Email email = new Email(senderAddress)
email.setSubject("JIRA Ticket erstellt: ${issue.summary}")
String content = "Content ----> by Issue2 ${issue.description}"
email.setBody(content)
mailServer.send(email)
}
}
Alas, it will not run in the Post Function like this:
import com.atlassian.jira.ComponentManager
import com.atlassian.jira.issue.Issue
//import com.atlassian.jira.issue.IssueManager
import com.atlassian.mail.Email
import com.atlassian.mail.server.MailServerManager
import com.atlassian.mail.server.SMTPMailServer
ComponentManager componentManager = ComponentManager.getInstance()
MailServerManager mailServerManager = componentManager.getMailServerManager()
SMTPMailServer mailServer = mailServerManager.getDefaultSMTPMailServer()
if (mailServer) {
if (true) {
//IssueManager issueManager = componentManager.getIssueManager()
//Issue issue = issueManager.getIssueObject("IN-376")
def grabEmail = {
(((it.split( "\\[Created via e-mail received from:")[1]).split("<")[1]).split(">")[0])
}
String senderAddress = grabEmail("${issue.description}")
Email email = new Email(senderAddress)
email.setSubject("JIRA Ticket erstellt: ${issue.summary}")
String content = "Content ----> by Issue2 ${issue.description}"
email.setBody(content)
mailServer.send(email)
}
}
I have no idea why the second code breaks since the code this is based on uses issue also as if it is implicitly defined. This Post function is the last to run.
I would also find hints as to debugging this problem helpful.
Thank you!

I'll post my comment as an answer: I did not find an error in any of the logs, then. Maybe I oversaw it, sorry, but I have changed a lot of config by now (installing JEMH trial) so I can not reproduce. Strangely enough, the message gets sent right now, so I have that ill feeling that I had some config in the Notifications Scheme wrong.
Thanks everyone for the help and time.

Related

How to use splash:mouse_press in Scrapy-Splash

I am trying yo click the display button on a website with no success and I really had no idea how to do it but I came across something that might work, splash:mouse_press. Will that work with scrapy-splash and if so how do I implement it?
import scrapy
from scrapy.spiders import Spider
from scrapy_splash import SplashRequest
from ..items import NameItem
class LoginSpider(scrapy.Spider):
name = "LoginSpider"
start_urls = ["http://www.starcitygames.com/buylist/"]
def parse(self, response):
return scrapy.FormRequest.from_response(
response,
formcss='#existing_users form',
formdata={'ex_usr_email': 'email#example.com', 'ex_usr_pass': 'password'},
callback=self.after_login
)
def after_login(self, response):
item = NameItem()
item["Name"] = response.css("div.bl-result-title::text").get()
return item
Welcome here (:
No need to overcomplicate things.
All you need is GET request to http://www.starcitygames.com/buylist/search?search-type=name&name=game
Well... of course you can vary params. But anyway you'll get all you want right in json format by this link.
It looks like even login isn't needed in fact.
Good luck.

How to extract full body content of a Bounced back email?

The above screenshot is the sample of the Bounced Back Mail received.
I'm using the following code to extract the Body of the mail.
function test()
{
var BouncedEmails = GmailApp.search("label:test The following message was undeliverable ");
for( var i=0;i<BouncedEmails.length;i++)
{
var Gmessage = GmailApp.getMessagesForThread(BouncedEmails[i]);
for(var j=0;j<Gmessage.length;j++)
{
var body = Gmessage[j].getPlainBody();
Logger.log(body);
}
}
}
But when I am doing this, I got the following output.
As you can see the last part of the Body is missing, that is :
I also tried using :
var body = Gmessage[j].getBody();
instead of "GetPlainBody()" but the output was still the same.
On using :
var body = Gmessage[j].getRawContent();
I got this as output for the missing part, which seems to me as some sort of encoding.
So my question is, how do i extract the full content of the Bounced Back Mail?
Thank You.
I finally found the answer to my own question.
This has worked for me and will pretty much work for anyone on our planet.
function test()
{
var BouncedEmails = GmailApp.search("label:test The following message was undeliverable ");
for( var i=0;i<BouncedEmails.length;i++)
{
var threadId = BouncedEmails[i].getId();
var id = Session.getEffectiveUser().getEmail();
var body = Gmail.Users.Threads.get(id, threadId, {format : 'full'});
var messages = body.messages;
var payLoad = messages[0].payload.parts[2];
var string = JSON.stringify(payLoad);
Logger.log(string);
}
}
The solutions provided by #AmitAgarwal and #ShyamKansagra would also work for some cases, but which solution to use depends on what is your exact requirement.
Don't use Logger.log as it truncates the output after a certain number of lines. Log the output in a spreadsheet and you'll see that the full body is extracted with getPlainBody() or getBody().
I recently published a Google Script to get all bounced emails in Gmail and logs them to a Google sheet. It is open so can build upon that script.
I also tried using getBody(), getPlainBody() and getRawContent() methods on bounced back emails. I noticed that these methods didn't give entire body of the email i.e. the part with technical details was skipped entirely in the logs.
So, I used this following code(all credits to #Amit Agarwal), which I found in the link which Amit has shared in his answer and it gave me entire body of bounced back email.
Here is the code:
var t = "in:anywhere from:(mailer-daemon#google.com OR mailer-daemon#googlemail.com)";
GmailApp.search(t,0,500).forEach(function(t)
{
t.getMessages().forEach(function(r)
{
if(r.getFrom().indexOf("mailer-daemon")!==-1)
{
var i=r.getPlainBody();
Logger.log(i);
}
}
)
}
)
It worked for me and gave the entire content in the logs itself. Hope this helps.

how i can reply to outlook email using python for the same sender by using below code?

I am trying to reply outlook email as we do manually it goes with previous conversations. But Below code is giving some error : Failed to send to the recipient address..I need to know how i can send it back to the person who sent me email..
import win32com.client, datetime
from datetime import timedelta
outlook =win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI") # to trigger outlook application
inbox = outlook.GetDefaultFolder(6) # 6 is used for the index of the folder
messages = inbox.Items
message = messages.GetLast()# message is treated as each mail in for loop
for message in messages:
if message.Subject=="request": # based on the subject replying to email
#body_content = message.body
message.Reply()
message.Body = "shortly will be processed!!!"
message.Send()
The reply is a MailItem returned by reply(). So try this:
reply = message.Reply()
reply.Body = "shortly will be processed!!!"
reply.Send()
continuing to above answer
to reply all:
`rplyall=message.ReplyAll()`
to reflect previous conversations:
`rplyall.Body="your message here"+rplyall.Body()`
`rplyall.Send()`
Since MailItem.Body is a String and it is not callable. Reference document
I think the correct code in #Akhil 's answer is
rplyall.Body = "your message here" + rplyall.Body
rplyall.Send()

having multiple sender in grails

I need to create a app for people which can send email, from anyone to anyone
I have tried using mail plugin in grails
mail {
host = "smtp.gmail.com"
port = 465
username = "adityasoni051293#gmail.com"
password = "aditya051293"
props = ["mail.smtp.auth":"true",
"mail.smtp.socketFactory.port":"465",
"mail.smtp.socketFactory.class":"javax.net.ssl.SSLSocketFactory",
"mail.smtp.socketFactory.fallback":"false"]
}
how ever I am not able to change the sender from application,
I have tried the following code in my controller
def defaultFrom = grailsApplication.config.grails.mail.default.from
String oldUsername = grailsApplication.config.grails.mail.mailSender.username
String oldPassword = grailsApplication.config.grails.mail.mailSender.password
// Change the properties here; send the email
try {
grailsApplication.config.grails.mail.default.from = "${parent_personal_data.email}"
grailsApplication.config.grails.mail.mailSender.username = "${parent_personal_data.email}"
grailsApplication.config.grails.mail.mailSender.password = "${parent_data.password}"
sendMail {
to "${employee_personal_data.email}"
subject "new task"
body "you have been added to project and you are given a task"
}
}
catch (Exception e) {
// catch block code
}
// Set the original settings back
finally {
grailsApplication.config.grails.mail.default.from = defaultFrom
grailsApplication.config.grails.mail.mailSender.username = oldUsername
grailsApplication.config.grails.mail.mailSender.password = oldPassword
but it is also using the id i set in config.groovy.
is there any way out.
or any other other plugin that I can use
please help I am waiting..... thanks
The problem you are facing is the fact the Grails Mail plugin is not designed to have it's host/port/username/password/connection properties changed at runtime. It's designed to work with one setting defined in Config.groovy.
If you need to be able to set that information at runtime then you will have to use Java Mail directly. Fortunately, you can look at the source code for the Grails Mail plugin to give you some ideas and even leverage the Spring Framework (Grails is built on Spring) for sending mail.
I had a similiar problem.
You can pass config to MailService#sendMail method.
`MailMessage sendMail(Config config, #DelegatesTo(strategy = Closure.DELEGATE_FIRST, value = MailMessageBuilder) Closure callable)`
Here is an example: https://github.com/rgorzkowski/grails-multiple-mail-senders/blob/master/grails-app/services/pl/stepwise/EmailNotificationService.groovy
and source code https://github.com/rgorzkowski/grails-multiple-mail-senders

setting up script to include google docs form data in email notification

I've setup a form using googledocs. I just want to have the actual data entered into the form emailed to me, as opposed to the generic response advising that the form has been completed.
I have no skill or experience with code etc, but was sure i could get this sorted. I've spent hours+hours and haven't had any luck.
My form is really basic.it has 5 fields. 4 of which are just text responses, and one multiple choice.
I found this tute online (http://www.labnol.org/internet/google-docs-email-form/20884/) which i think sums up what i'm trying to do, but have not been able to get it to work.
from this site i entered the following code:
function sendFormByEmail(e)
{
var email = "reports.mckeir#gmail.com";
var subject = "Google Docs Form Submitted";
var s = SpreadsheetApp.getActiveSheet();
var headers = s.getRange(1,1,1,s.getLastColumn()).getValues()[0];
var message = "";
for(var i in headers)
message += headers[i] + ' = '+ e.namedValues[headers[i]].toString() + "\n\n";
MailApp.sendEmail(email, subject, message);
}
To this, i get the following response: ->
Your script, Contact Us Form Mailer, has recently failed to finish successfully. A summary of the failure(s) is shown below. To configure the triggers for this script, or change your setting for receiving future failure notifications, click here.
The script is used by the document 100% Club.
Details:
Start Function Error Message Trigger End
12/3/12 11:06 PM sendFormByEmail TypeError: Cannot call method "toString" of undefined. (line 12) formSubmit 12/3/12 11:06 PM
Is anyone able to help shed some light on this for me? I'm guessing i'm not including some data neeeded, but i honestly have no clue.
Workaround http://www.labnol.org/internet/google-docs-email-form/20884/
You have to setup app script to forward the data as email.
I'll point to the comment above that solved it for me: https://stackoverflow.com/a/14576983/134335
I took that post a step further:
I removed the normal notification. The app script makes that generic text redundant and useless now
I modified the script to actually parse the results and build the response accordingly.
function sendFormByEmail(e)
{
var toEmail = "changeme";
var name = "";
var email = "";
// Optional but change the following variable
// to have a custom subject for Google Docs emails
var subject = "Google Docs Form Submitted";
var message = "";
// The variable e holds all the form values in an array.
// Loop through the array and append values to the body.
var s = SpreadsheetApp.getActiveSheet();
var headers = s.getRange(1,1,1,s.getLastColumn()).getValues()[0];
// Credit to Henrique Abreu for fixing the sort order
for(var i in headers) {
if (headers[i] = "Name") {
name = e.namedValues[headers[i]].toString();
}
if (headers[i] = "Email") {
email = e.namedValues[headers[i]].toString();
}
if (headers[i] = "Subject") {
subject = e.namedValues[headers[i]].toString();
}
if (headers[i] = "Message") {
message = e.namedValues[headers[i]].toString();
}
}
// See https://developers.google.com/apps-script/reference/mail/mail-app#sendEmail(String,String,String,Object)
var mailOptions = {
name: name,
replyTo: email,
};
// This is the MailApp service of Google Apps Script
// that sends the email. You can also use GmailApp here.
MailApp.sendEmail(toEmail, subject, message, mailOptions);
// Watch the following video for details
// http://youtu.be/z6klwUxRwQI
// By Amit Agarwal - www.labnol.org
}
The script utilized in the example is extremely generic but very resilient to change because the message is built as a key/value pair of the form fields submitted.
If you use my script you'll have to tweak the for loop if statements to match your fields verbatim. You'll also want to edit the toEmail variable.
Thanks again for the question and answers. I was about to ditch Google Forms as the generic response was never enough for what I was trying to do.
Lastly, in response to the actual problem above "toString of undefined" specifically means one of the form fields was submitted as blank. If I had to guess, I would say the author only used this for forms where all the fields were required or a quick undefined check would've been put in place.
Something like the following would work:
for(var i in headers) {
var formValue = e.namedValues[headers[i]];
var formValueText = "";
if (typeof(formValue) != "undefined") {
formValueText = formValue.toString();
}
message += headers[i] + ' = '+ formvalueText + "\n\n";
}
I haven't tested this precisely but it's a pretty standard way of making sure the object is defined before trying methods like toString() that clearly won't work.
This would also explain Jon Fila's answer. The script blindly assumes all of the header rows in the response are sent by the form. If any of the fields aren't required or the spreadsheet has fields that are no longer in the form, you'll get a lot of undefined objects.
The script could've been coded better but I won't fault the author as it was clearly meant to be a proof of concept only. The fact that they mention the replyTo correction but don't give any examples on implementing it made it perfectly clear.
If this is a Google Form, do you have any extra columns in your spreadsheet that are not on the form? If you delete those extra columns then it started working for me.
You don't need to use a script. Simply go to Tools >> Notification Rules on your Google Spreadsheet. There you can change the settings to receive an email with your desired information every time the document is changed.