How to use getbeans and relationship field - suitecrm

I'm setting up a logic hook in suitecrm to allow nc case to emailed to the department the issue is raised to however; I keep getting the error message "Could not find Users within the department NC is issued to; indicating that dept_array is equivalent to zero. I'm to using getbeans and relationship tables. I created the relationship dept_department_nccas_nc_case in suitecrm but there's no data inside the table so I'm wondering if that's the reason or if my syntax is incorrect.
class nc_email_notification {
public function email_notification(&$bean, $events, $arguments){
/*define 'review_pending' as string constant */
/*Get sugar email engine*/
$email = new SugarPHPMailer();
$email->From = 'suitecrm#gmail.com';
$email->FromName ='SuiteCRM';
/*Get the Department NC was Issued to */
$dept_array= $bean->get_linked_beans('dept_department_nccas_nc_case','dept_Department_sugar');
if(count($dept_array)==0){
/*log error*/
$GLOBALS['log']->fatal("Could not find the department NC was issued to: ". $bean->name);
}else{
/* Get email of users within the Department NC is issued to */
$user_array = $dept_array[0]->get_linked_beans('dept_department_users','User');
if(count($user_array)==0){
/*log error*/
$GLOBALS['log']->fatal("Could not find Users within the department NC is issued to: ". $bean->name);
}else{
$address=getDepartmentUsersEmail($user_array);
}
/*Get the Department NC was raised by */
$raised_dept_array= $bean->get_linked_beans('dept_department_nccas_nc_case_1','dept_Department_sugar');
if(count($raised_dept_array)==0){
/*log error*/
$GLOBALS['log']->fatal("Could not find the department NC was raised by: ". $bean->name);
}else {
/*Get email of users within the Department NC is raised by*/
$raised_user_array = $raised_dept_array[0]->get_linked_beans('dept_department_users','User');
if(count($raised_user_array)==0){
/*log error*/
$GLOBALS['log']->fatal("Could not find Users within the department NC is raised by: ". $bean->name);
}
else {
$r_user_address = getDepartmentUsersEmail($raised_user_array);
}
}
/*Get the Quality Systems Department*/
//$qual_dept=$dept_array[0]->retrieve)by)string_fields(array('name' => 'Quality Systems' ));
//$qual_dept->load_relationship('dept_department_email_addresses_primary');
/* Send email to Manager */
$rev_email = 'ramon#gmail.com';
/*Get NC Action for the NC Case*/
$action_array = $bean->get_linked_beans('nccas_nc_case_ncact_nc_action','ncact_NC_Action_sugar');
/* Get sugar template engine */
$xtpl = new XTemplate("XTemplate/NCEmailTemplate.html");
/*GEt the URL for the NC Case */
$url = $GLOBALS['sugar_config']['site_url'].'index.php?module=ncase_NonConformance&action=DetailView&record='.$bean->id;
$xtpl -> assign('URL', $url);
/* Get NC Status */
$nc_status=trim($bean->getFieldValue('status'));
/* Get NC ID */
$id = $bean->getFieldValue('id');
if(empty($bean->fetched_row['id'])){
$email=createNCEmail($email,$rev_email,'New NC Email Notification',$bean,$xtpl);
/* Send email to Quality System Manager */
$email->addaddress($rev_email);
/* Send email to users of Issued to department */
foreach($address as $uemail){
$email->addAddress($uemail);
}
}else {
if (strcasecmp ($nc_status,'review_pending')==0){
/* Set Email Subject */
$email->Subject = 'NC Case: '. ''. $bean->name . ' '. ' is pending review';
/* Send email to users of Raised by department */
foreach($r_user_address as $uemail){
$email->addAddress($uemail);
}
/* Send email to Quality System Manager */
$email->addaddress($rev_email);
/* Create email message using email template */
$email=createNCEmailwithAction($email,$action_array,$bean,$xtpl);
} else if (strcasecmp ($nc_status,'Closed')==0){
/* Set Email Subject */
$email->Subject = 'NC Case: '. ''. $bean->name . ''. ' is Closed';
/* Send email to users of Raised by department */
foreach($r_user_address as $uemail){
$email->addAddress($uemail);
}
/* Send email to Issued to Department */
foreach($address as $iemail){
$email->addAddress($iemail);
}
/* Create email message using email template*/
$email=createNCEmailwithAction($email,$action_array,$bean,$xtpl);
} else{
If ($bean->fetched_row['description'] != $bean->description){
/* Set Email Subject */
$email->Subject = 'NC Case: ' .''. $bean->name .''. ' has been modified';
/* Create email message using email template */
$email=createNCEmailwithAction($email,$action_array,$bean,$xtpl);
/* Build appropriate email list */
foreach($address as $uemail){
$email->addAddress($uemail);
}
/* Send email to Quality System Manager */
$email->addaddress($rev_email);
}
}
}

Relationship names are tricky! I always get them wrong so here is a snippet that will let you find the exact name
$m1 = 'Users';
$m2 = 'ACLRoles';
print_r(getRelationshipByModules($m1, $m2));
$m2 = 'Users';
$m1 = 'ACLRoles';
print_r(getRelationshipByModules($m1, $m2));
Please note that the order matters so that's why I repeat the sentence twice but in different order.
Change m1/m2 for the module you want to know the relationship name and then do get_linked_beans

Related

What protocol does SnowFlake JDBC driver use?

I'm trying to find out what protocol the SnowFlake JDBC library uses to communicate with SnowFlake. I see hints here and there that it seems to be using HTTPS as the protocol. Is this true?
To my knowledge, other JDBC libraries like for example for Oracle or PostgreSQL use the lower level TCP protocol to communicate with their database servers, and not the application-level HTTP(S) protocol, so I'm confused.
My organization only supports securely routing http(s)-based communication. Can I use this snowflake jdbc library then?
I have browsed all documentation that I could find, but wasn't able to answer this question.
My issue on GitHub didn't get an answer either.
Edit: Yes, I've seen this question, but I don't feel that it answers my question. SSL/TLS is an encryption, but that doesn't specify the data format.
It looks like the jdbc driver uses HTTP Client HttpUtil.initHttpClient(httpClientSettingsKey, null);, as you can see in here
The HTTP Utility Class is available here
Putting an excerpt of the session open method here in case the link goes bad/dead.
/**
* Open a new database session
*
* #throws SFException this is a runtime exception
* #throws SnowflakeSQLException exception raised from Snowflake components
*/
public synchronized void open() throws SFException, SnowflakeSQLException {
performSanityCheckOnProperties();
Map<SFSessionProperty, Object> connectionPropertiesMap = getConnectionPropertiesMap();
logger.debug(
"input: server={}, account={}, user={}, password={}, role={}, database={}, schema={},"
+ " warehouse={}, validate_default_parameters={}, authenticator={}, ocsp_mode={},"
+ " passcode_in_password={}, passcode={}, private_key={}, disable_socks_proxy={},"
+ " application={}, app_id={}, app_version={}, login_timeout={}, network_timeout={},"
+ " query_timeout={}, tracing={}, private_key_file={}, private_key_file_pwd={}."
+ " session_parameters: client_store_temporary_credential={}",
connectionPropertiesMap.get(SFSessionProperty.SERVER_URL),
connectionPropertiesMap.get(SFSessionProperty.ACCOUNT),
connectionPropertiesMap.get(SFSessionProperty.USER),
!Strings.isNullOrEmpty((String) connectionPropertiesMap.get(SFSessionProperty.PASSWORD))
? "***"
: "(empty)",
connectionPropertiesMap.get(SFSessionProperty.ROLE),
connectionPropertiesMap.get(SFSessionProperty.DATABASE),
connectionPropertiesMap.get(SFSessionProperty.SCHEMA),
connectionPropertiesMap.get(SFSessionProperty.WAREHOUSE),
connectionPropertiesMap.get(SFSessionProperty.VALIDATE_DEFAULT_PARAMETERS),
connectionPropertiesMap.get(SFSessionProperty.AUTHENTICATOR),
getOCSPMode().name(),
connectionPropertiesMap.get(SFSessionProperty.PASSCODE_IN_PASSWORD),
!Strings.isNullOrEmpty((String) connectionPropertiesMap.get(SFSessionProperty.PASSCODE))
? "***"
: "(empty)",
connectionPropertiesMap.get(SFSessionProperty.PRIVATE_KEY) != null
? "(not null)"
: "(null)",
connectionPropertiesMap.get(SFSessionProperty.DISABLE_SOCKS_PROXY),
connectionPropertiesMap.get(SFSessionProperty.APPLICATION),
connectionPropertiesMap.get(SFSessionProperty.APP_ID),
connectionPropertiesMap.get(SFSessionProperty.APP_VERSION),
connectionPropertiesMap.get(SFSessionProperty.LOGIN_TIMEOUT),
connectionPropertiesMap.get(SFSessionProperty.NETWORK_TIMEOUT),
connectionPropertiesMap.get(SFSessionProperty.QUERY_TIMEOUT),
connectionPropertiesMap.get(SFSessionProperty.TRACING),
connectionPropertiesMap.get(SFSessionProperty.PRIVATE_KEY_FILE),
!Strings.isNullOrEmpty(
(String) connectionPropertiesMap.get(SFSessionProperty.PRIVATE_KEY_FILE_PWD))
? "***"
: "(empty)",
sessionParametersMap.get(CLIENT_STORE_TEMPORARY_CREDENTIAL));
HttpClientSettingsKey httpClientSettingsKey = getHttpClientKey();
logger.debug(
"connection proxy parameters: use_proxy={}, proxy_host={}, proxy_port={}, proxy_user={},"
+ " proxy_password={}, non_proxy_hosts={}, proxy_protocol={}",
httpClientSettingsKey.usesProxy(),
httpClientSettingsKey.getProxyHost(),
httpClientSettingsKey.getProxyPort(),
httpClientSettingsKey.getProxyUser(),
!Strings.isNullOrEmpty(httpClientSettingsKey.getProxyPassword()) ? "***" : "(empty)",
httpClientSettingsKey.getNonProxyHosts(),
httpClientSettingsKey.getProxyProtocol());
// TODO: temporarily hardcode sessionParameter debug info. will be changed in the future
SFLoginInput loginInput = new SFLoginInput();
loginInput
.setServerUrl((String) connectionPropertiesMap.get(SFSessionProperty.SERVER_URL))
.setDatabaseName((String) connectionPropertiesMap.get(SFSessionProperty.DATABASE))
.setSchemaName((String) connectionPropertiesMap.get(SFSessionProperty.SCHEMA))
.setWarehouse((String) connectionPropertiesMap.get(SFSessionProperty.WAREHOUSE))
.setRole((String) connectionPropertiesMap.get(SFSessionProperty.ROLE))
.setValidateDefaultParameters(
connectionPropertiesMap.get(SFSessionProperty.VALIDATE_DEFAULT_PARAMETERS))
.setAuthenticator((String) connectionPropertiesMap.get(SFSessionProperty.AUTHENTICATOR))
.setOKTAUserName((String) connectionPropertiesMap.get(SFSessionProperty.OKTA_USERNAME))
.setAccountName((String) connectionPropertiesMap.get(SFSessionProperty.ACCOUNT))
.setLoginTimeout(loginTimeout)
.setAuthTimeout(authTimeout)
.setUserName((String) connectionPropertiesMap.get(SFSessionProperty.USER))
.setPassword((String) connectionPropertiesMap.get(SFSessionProperty.PASSWORD))
.setToken((String) connectionPropertiesMap.get(SFSessionProperty.TOKEN))
.setPasscodeInPassword(passcodeInPassword)
.setPasscode((String) connectionPropertiesMap.get(SFSessionProperty.PASSCODE))
.setConnectionTimeout(httpClientConnectionTimeout)
.setSocketTimeout(httpClientSocketTimeout)
.setAppId((String) connectionPropertiesMap.get(SFSessionProperty.APP_ID))
.setAppVersion((String) connectionPropertiesMap.get(SFSessionProperty.APP_VERSION))
.setSessionParameters(sessionParametersMap)
.setPrivateKey((PrivateKey) connectionPropertiesMap.get(SFSessionProperty.PRIVATE_KEY))
.setPrivateKeyFile((String) connectionPropertiesMap.get(SFSessionProperty.PRIVATE_KEY_FILE))
.setPrivateKeyFilePwd(
(String) connectionPropertiesMap.get(SFSessionProperty.PRIVATE_KEY_FILE_PWD))
.setApplication((String) connectionPropertiesMap.get(SFSessionProperty.APPLICATION))
.setServiceName(getServiceName())
.setOCSPMode(getOCSPMode())
.setHttpClientSettingsKey(httpClientSettingsKey);
// propagate OCSP mode to SFTrustManager. Note OCSP setting is global on JVM.
HttpUtil.initHttpClient(httpClientSettingsKey, null);
SFLoginOutput loginOutput =
SessionUtil.openSession(loginInput, connectionPropertiesMap, tracingLevel.toString());
isClosed = false;
authTimeout = loginInput.getAuthTimeout();
sessionToken = loginOutput.getSessionToken();
masterToken = loginOutput.getMasterToken();
idToken = loginOutput.getIdToken();
mfaToken = loginOutput.getMfaToken();
setDatabaseVersion(loginOutput.getDatabaseVersion());
setDatabaseMajorVersion(loginOutput.getDatabaseMajorVersion());
setDatabaseMinorVersion(loginOutput.getDatabaseMinorVersion());
httpClientSocketTimeout = loginOutput.getHttpClientSocketTimeout();
masterTokenValidityInSeconds = loginOutput.getMasterTokenValidityInSeconds();
setDatabase(loginOutput.getSessionDatabase());
setSchema(loginOutput.getSessionSchema());
setRole(loginOutput.getSessionRole());
setWarehouse(loginOutput.getSessionWarehouse());
setSessionId(loginOutput.getSessionId());
setAutoCommit(loginOutput.getAutoCommit());
// Update common parameter values for this session
SessionUtil.updateSfDriverParamValues(loginOutput.getCommonParams(), this);
String loginDatabaseName = (String) connectionPropertiesMap.get(SFSessionProperty.DATABASE);
String loginSchemaName = (String) connectionPropertiesMap.get(SFSessionProperty.SCHEMA);
String loginRole = (String) connectionPropertiesMap.get(SFSessionProperty.ROLE);
String loginWarehouse = (String) connectionPropertiesMap.get(SFSessionProperty.WAREHOUSE);
if (loginDatabaseName != null && !loginDatabaseName.equalsIgnoreCase(getDatabase())) {
sqlWarnings.add(
new SFException(
ErrorCode.CONNECTION_ESTABLISHED_WITH_DIFFERENT_PROP,
"Database",
loginDatabaseName,
getDatabase()));
}
if (loginSchemaName != null && !loginSchemaName.equalsIgnoreCase(getSchema())) {
sqlWarnings.add(
new SFException(
ErrorCode.CONNECTION_ESTABLISHED_WITH_DIFFERENT_PROP,
"Schema",
loginSchemaName,
getSchema()));
}
if (loginRole != null && !loginRole.equalsIgnoreCase(getRole())) {
sqlWarnings.add(
new SFException(
ErrorCode.CONNECTION_ESTABLISHED_WITH_DIFFERENT_PROP, "Role", loginRole, getRole()));
}
if (loginWarehouse != null && !loginWarehouse.equalsIgnoreCase(getWarehouse())) {
sqlWarnings.add(
new SFException(
ErrorCode.CONNECTION_ESTABLISHED_WITH_DIFFERENT_PROP,
"Warehouse",
loginWarehouse,
getWarehouse()));
}
// start heartbeat for this session so that the master token will not expire
startHeartbeatForThisSession();
}

Player command failed: Premium required. However i have premium

Im am using a family account (premium) and this code returns a'Premium required' error. My code is as follows:
device_id = '0d1841b0976bae2a3a310dd74c0f3df354899bc8'
def playSpotify():
client_credentials_manager = SpotifyClientCredentials(client_id='<REDACTED>', client_secret='<REDACTED>')
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
playlists = sp.user_playlists('gh8gflxedxmp4tv2he2gp92ev')
#while playlists:
#for i, playlist in enumerate(playlists['items']):
#print("%4d %s %s" % (i + 1 + playlists['offset'], playlist['uri'], playlist['name']))
#if playlists['next']:
#playlists = sp.next(playlists)
#else:
#playlists = None
#sp.shuffle(true, device_id=device_id)
#sp.repeat(true, device_id=device_id)
sp.start_playback(device_id=device_id, context_uri='spotify:playlist:4ndG2qFEFt1YYcHYt3krjv')
When using SpotifyClientCredentials the token that is generated doesn't belong to any user but to an app, hence the error message.
What you need to do is use SpotifyOAuth instead. So to initialize spotipy, just do:
sp = spotipy.Spotify(auth_manager=spotipy.SpotifyOAuth())
This will open a browser tab and require you to sign in to your account.

How can I use a table in LUA for pinging multiple devices and detecting change in variable status

I am trying to ping a number of IP address on a local network at defined intervals and then send a message only when a device connects. I have managed to get it to work for a single device, but when I add additional devices to the table the code fails.
Many thanks in advance.
An earlier version without the table and just a single IP address works perfectly. But adding the table and the "for key,value loop" only works if a single entry is in the table.
local tble = {
["device name"] = "192.168.1.204"
}
for key,value in pairs(tble) do
statuscheckIP=os.execute("arping -f -w 3 " .. value)
if statuscheckIP ~= lastcheckIP then
if statuscheckIP == 0 and lastcheckIP == 256 then
subject ="" ..key.. " , ( IP Address " ..value.. ") Connected"
message = "Connection Alert\nThe device named " ..key.. ", with the IP address " ..value.. " has just connected to the WiFi network"
--send email notification
luup.call_action("urn:upnp-org:serviceId:SmtpNotification1", "SendEmail", { Recipient_Name="SomeOne", Recipient_eMail="someone#somewhere.com", Subject= subject, Message=message }, 24)luup.call_action("urn:upnporg:serviceId:SmtpNotification1","ResetCount",{}, 24)
else
end
end
end
lastcheckIP = statuscheckIP
The code you posted is valid. There are not many reasons why this would fail due to more entries in your table.
os.execute Execute an operating system shell command. This is like the C system() function. The system dependent status code is returned.
Running os.execute will start a arping and return an exitcode. Then you are comparing that statuscheckIP == 0 a lastcheckIP == 256. The if before is redundant. If true you are sending your message and continuing.
After worked though all entries you are setting lastcheckIP to statusCheckIP and this is propably your error. It should be before the last if and inside your loop. But even then does not make sense if 0 is the only correct return code. If lastcheckIP is set to any other value your both if's will never go true again.
Either your last line lastcheckIP = statuscheckIP is wrongly placed, lastcheckIP was never initialized to 256 or you should rethink your whole program.
EDIT:
After understanding the intention of the provided program, I've created a probably working example. This should show you, how to easily use tables in Lua as a structures. I was not able to test the following code.
local WAIT_TIME = 10
local STATUS_CODE_CONNECTED = 0
local STATUS_CODE_NOT_CONNECT = 256 -- not sure about this (return code from arping for failure)
local device_table =
{
["device_name1"] =
{
ip = "<ip address>",
status_code = STATUS_CODE_NOT_CONNECT
},
["device_name1"] =
{
ip = "<ip address>",
status_code = STATUS_CODE_NOT_CONNECT
}
-- , ...
}
while true do
-- check for changed return codes
for device_name, device in pairs(device_table) do
local temp_status_code = os.execute("arping -f -w 3 " .. device.ip)
-- status code changed
if temp_status_code ~= device.status_code then
-- device connected
if temp_status_code == STATUS_CODE_CONNECTED then
local subject = "" .. device_name .. " , ( IP Address " .. device.ip .. ") Connected"
local message = "Connection Alert\nThe device named " .. device_name .. ", with the IP address " .. device.ip .. " has just connected to the WiFi network"
--send email notification
luup.call_action(
"urn:upnp-org:serviceId:SmtpNotification1",
"SendEmail",
{
Recipient_Name = "SomeOne",
Recipient_eMail = "someone#somewhere.com",
Subject = subject,
Message = message
}, 24)
luup.call_action(
"urn:upnporg:serviceId:SmtpNotification1",
"ResetCount",
{ }, 24)
end
-- update last device status_code if changed
device.status_code = temp_status_code
end
end
os.execute("sleep " .. tonumber(WAIT_TIME)) -- wait some time for next check
end
If I've understand you wrongly and you either do not want to have this program run all the time or do not want to have all addresses in a table then you should ask again or somewhere else because that would be out off topic.

CMS (PKCS#7) RecipientInfo

I am actually working on a function which should extract RecipientInfo from PKCS7 mime encrypted message. The reason why I want to do this is, that I want to get all mail addresses (or at least the keyids/fingerprints) the message is encrypted for.
Well - I tried something out and created something like this (indata is a *.p7m attachment content, indata_len the strlen of indata):
char *indata;
int indata_len, i;
PKCS7 *p7 = NULL;
BIO *bcont = NULL;
CMS_ContentInfo *cms = NULL;
STACK_OF(CMS_RecipientInfo) *recipients = NULL;
CMS_RecipientInfo *recip = NULL;
BIO *encMessage = BIO_new(BIO_s_mem());
if (encMessage == NULL) {
goto clean_exit;
}
if(!BIO_write(encMessage, indata, indata_len)) {
goto clean_exit;
}
cms = SMIME_read_CMS(encMessage,NULL);
if (cms == NULL ) {
goto clean_exit;
}
recipients = CMS_get0_RecipientInfos(cms);
if (recipients == NULL) {
goto clean_exit;
}
for (i=0; i< sk_CMS_RecipientInfo_num(recipients); i++) {
recip = sk_CMS_RecipientInfo_value(recipients, i);
if( recip == NULL || CMS_RecipientInfo_type(recip) != CMS_RECIPINFO_TRANS ) {
continue;
}
int r;
ASN1_OCTET_STRING **keyid;
X509_NAME **issuer;
ASN1_INTEGER **sno;
r = CMS_RecipientInfo_ktri_get0_signer_id(recip, keyid, issuer, sno);
if (!r) {
continue;
}
printf("Key: %s\n", keyid);
}
I get no error (checked with ERR_get_error()) but keyid, issuer and sno stay "null", output of above code is:
Key: (null)
So my question is, is it even possible to get that information of an encrypted message or is there just an error in reasoning on my side?
If it is possible to get that data, can someone give me a hint?
If it is not possible, whats the default (best) way to check which private key to use for decryption. Since there can be more than one S/Mime certificate/key for a single user. E.g. creating new key since the old one is lost or just get a new cert/key combination from provider, ...
Imho, looping through all keys could take some time if the message is really big.
Best regards,
Max
I don't know how to fix your code, but I have a couple of openssl commands and a python script to solve your task:
You can run the following command to get the list of all serial numbers
of the recipient keys in an encrypted file MYMAIL:
openssl smime -pk7out -inform DER -in MYMAIL \
| openssl pkcs7 -noout -print \
| grep serial
This will print the serial number as decimal numbers of all recipients, i.e. serial numbers of certificates for which the file MYMAIL has been encrypted for. For a given certificate file CERTFILE.0, the command
openssl x509 -in CERTFILE.0 -serial -noout
prints its serial number as a hexadecimal number. Now, you can to combine the serial numbers of the certificates you have with the serial numbers mentioned in MYMAIL.
I've wrote a python script that does this and that can be used to replace the default smime_decrypt_command in mutt, such that when decrypting an E-Mail, the correct private key is chosen for decryption: https://github.com/t-wissmann/dotfiles/blob/master/utils/smime-recipient-list.py
For the case that the url breaks, I'm pasting the entire script below.
#!/usr/bin/env python3
"""
Given an smime encrypted file and some smime certificates,
tell for which of the smime certificates, the encrypted file has been
encrypted for.
"""
import argparse
import os
import re
import subprocess
import sys
import textwrap
class Openssl:
def __init__(self, openssl_command):
self.openssl_command = openssl_command
def get_certificate_serial_number(self, certificate_file):
"""Given a certificate_file filepath, return its serial number as an int"""
command = [self.openssl_command, 'x509', '-in', certificate_file, '-serial', '-noout']
proc = subprocess.run(command, stdout=subprocess.PIPE)
# output should be of the form 'serial=HEXADECIMALNUMBER'
try:
return int(proc.stdout.decode().replace('serial=', ''), 16)
except ValueError:
print("Can not read file: {}".format(certificate_file), file=sys.stderr)
def smime_pk7out(self, encrypted_file):
"""run smime -pk7out, return its output"""
command = [self.openssl_command, 'smime', '-pk7out']
command += ['-inform', 'DER', '-in', encrypted_file]
proc = subprocess.run(command, stdout=subprocess.PIPE)
return proc.stdout.decode()
def pkcs7_serial_numbers(self, pk7buf):
"""extract all serial numbers via openssl pkcs7 -noout -print"""
command = [self.openssl_command, 'pkcs7', '-noout', '-print']
proc = subprocess.run(command, stdout=subprocess.PIPE, text=True, input=pk7buf)
for match in re.finditer('serial: ([0-9]+)', proc.stdout):
yield int(match.group(1))
def list_recipient_serial_numbers(self, encrypted_file):
"""Do essentially:
openssl smime -pk7out -inform DER -in MYMAIL \
| openssl pkcs7 -noout -print \
| grep serial
"""
pk7out = self.smime_pk7out(encrypted_file)
return list(self.pkcs7_serial_numbers(pk7out))
def smime_decrypt(self, private_key, certificate, filepath, passin='stdin'):
"""encrypt the given filepath and print to stdout"""
command = [self.openssl_command, 'smime', '-decrypt', '-passin', passin]
command += ['-inform', 'DER', '-in', filepath]
command += ['-inkey', private_key]
command += ['-recip', certificate]
subprocess.run(command)
def main():
"""main"""
description = "Detect recipients of smime encrypted files"
epilog = textwrap.dedent(r"""
E.g. you can decrypt an email with the command that picks the
private key automatically:
{} \
--passin stdin --decrypt \
--private-key ~/.smime/keys/* \
-- mymail ~/.smime/certificates/*
If you use mutt, you can set
set smime_decrypt_command="\
~/path/to/smime-recipient-list.py --passin stdin --decrypt \
--private-key ~/.smime/keys/* \
-- %f ~/.smime/certificates/KEYPREFIX.*"
where KEYPREFIX is the prefix of your key (i.e. without the .0 or .1 suffix).
""".format(sys.argv[0]))
parser = argparse.ArgumentParser(
description=description,
epilog=epilog,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('encryptedfile', help='the encrypted file')
parser.add_argument('certificates',
nargs='+',
help='the smime certificate files')
parser.add_argument('--openssl', default='openssl', help='openssl command name')
parser.add_argument('--list-serials', action='store_true',
help='list serial numbers of certifacts')
parser.add_argument('--print-path', action='store_true',
help='print path of recipient certificates')
parser.add_argument('--private-keys', nargs='*', default=[], help='private keys for decrypt')
parser.add_argument('--decrypt', action='store_true',
help='decrypt using one of the private keys passed.\
the key must have the same file name as the certificate.')
parser.add_argument('--passin', default='stdin',
help='default openssl -passin parameter for decrypt')
args = parser.parse_args()
openssl = Openssl(args.openssl)
# get the serial number of every smime-certfile:
serialnum2cert = {}
for i in args.certificates:
serialnum2cert[openssl.get_certificate_serial_number(i)] = i
if args.list_serials:
for serialnum, keyfile in serialnum2cert.items():
print("{} --> {}".format(keyfile, serialnum))
recipients = openssl.list_recipient_serial_numbers(args.encryptedfile)
if args.print_path or args.decrypt:
matching_keys = []
for i in recipients:
if i in serialnum2cert:
matching_keys.append(serialnum2cert[i])
if args.print_path:
for i in matching_keys:
print(i)
if args.decrypt:
private_keys = {}
for filepath in args.private_keys:
private_keys[os.path.basename(filepath)] = filepath
key_found = None
for fp in matching_keys:
if os.path.basename(fp) in private_keys:
priv_key_path = private_keys[os.path.basename(fp)]
# print("We can use {} and {}".format(priv_key_path, fp))
key_found = (priv_key_path, fp)
if key_found is None:
print("No matching private key found.", file=sys.stderr)
sys.exit(1)
openssl.smime_decrypt(key_found[0], key_found[1],
args.encryptedfile, passin=args.passin)
if __name__ == "__main__":
main()

Emails are going in spam in cake php

Here are my code:-
//Sending mail
if ($this->Session->read('Enrollment.personalinfo_language') == 'English') {
$language = "english";
$subject = "Thank you for submitting your enrollment request to Apna Energy.";
} else {
$language = "spanish";
$subject = "Gracias por enviar su solicitud de inscripci?n a Apna Energy.";
}
$details = $this->Session->read('Enrollment');
$details['plan_name'] = $product['Product']['name'];
$details['rate'] = $plan_rate;
$details['term'] = $product['Term']['term'];
$this->Email->sendAs = 'html';
$this->Email->from = 'Apna Energy <contact#apnaenergy.com>';
$this->Email->to = $this->Session->read('Enrollment.personalinfo_first_name') . ' ' . $this->Session->read('Enrollment.personalinfo_last_name') . '<' . $this->Session->read('Enrollment.personalinfo_email') . '>';
$this->Email->bcc = array('my#mail.com');
$this->Email->subject = $subject;
$this->set('details', $details);
if ($this->Session->read('Enrollment.personalinfo_language') == 'English') {
$template = "enrollment_confirmation";
} else {
$template = "enrollment_confirmation";
}
$this->Email->template = $template;
$this->Email->send();
My problem is if customer fill form they are receiving mail in his/her spam folder.. customer's mail id in "to".. and my mail id in "BCC" for me mail are coming fine in my inbox folder..
I followed two URL but they didn't work out for me..
Cakephp emails going to spam
How do you make sure email you send programmatically is not automatically marked as spam?
Guide me in right direction..
Thanks!!
by using SMTP
with normal PHP your server must be configured properly which is not easy to do as a beginner (MX records need to match the servers ip etc).
So just always stick to SMTP as mailing gateway and you will be fine.
PS: I don't think it has anything to do with your code in general, although it is not very beautiful. for instance: you should cast the array you read from the session to avoid notices thrown:
$details = (array)$this->Session->read('Enrollment');

Resources